Ubuntu下使用CodeBlocks进行多线程编程

因为项目开发需要, 我要在Ubuntu中使用多线程编程进行,以便能够在不影响主线程的情况下, 读写虚拟环境中的相关数据.

强烈建议先阅读[C/C++ 多线程(程序猿面试重点)CodeBlocks-CB的pthreads使用]了解Ubuntu下使用多线程编程时的基本理论知识. 里面有很详细的解释说明

初始代码

这里我首先参考了部分网上博客, 写了如下Read&Write的demo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#define MAX 10
int test_multiple_threads_R_and_S = 10;
void *set_thread(void *)
{
int i;
for(;;){
++test_multiple_threads_R_and_S;
sleep(2);
if( test_multiple_threads_R_and_S >= 20){
pthread_exit(NULL); // 测试退出子线程.
}
}
}

void *read_thread(void *)
{
int i;
for(;;){
printf("the value of test is %d\n", test_multiple_threads_R_and_S);
sleep(1);
}
}

int main(int argc, const char *argv[])
{
int i = 0;
int ret = 0;
pthread_t id1,id2;

ret = pthread_create(&id1, NULL, set_thread, NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}

ret = pthread_create(&id2, NULL, read_thread, NULL);
if(ret)
{
printf("Create pthread error!\n");
return 1;
}

pthread_join(id1,NULL);
pthread_join(id2,NULL);

return 0;
}

直接运行上述代码可能会出现报错对‘pthread_create’未定义的引用, 可以参考[codeblocks 多线程编程时出现:对pthread_create未定义的引用,解决方法]中的方法进行调试.

如果上述程序运行理想的话, 运行结果应该如下.

运行结果

写入线程运行到将test变量增加到20之后, 被kill. 读线程正常运行直到主进程结束. (此时需要了解进程线程之间的关系, 以及程序中的线程进程的生命周期.

到此测试结束, 运行成功.

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信