Ubuntu下使用CodeBlocks进行多线程编程
因为项目开发需要, 我要在Ubuntu中使用多线程编程进行,以便能够在不影响主线程的情况下, 读写虚拟环境中的相关数据.
强烈建议先阅读[C/C++ 多线程(程序猿面试重点)CodeBlocks-CB的pthreads使用]了解Ubuntu下使用多线程编程时的基本理论知识. 里面有很详细的解释说明
初始代码
这里我首先参考了部分网上博客, 写了如下Read&Write的demo.
1#include <pthread.h>
2#include <stdio.h>
3#include <sys/time.h>
4#include <string.h>
5#include <unistd.h>
6#define MAX 10
7int test_multiple_threads_R_and_S = 10;
8void *set_thread(void *)
9{
10 int i;
11 for(;;){
12 ++test_multiple_threads_R_and_S;
13 sleep(2);
14 if( test_multiple_threads_R_and_S >= 20){
15 pthread_exit(NULL); // 测试退出子线程.
16 }
17 }
18}
19
20void *read_thread(void *)
21{
22 int i;
23 for(;;){
24 printf("the value of test is %d\n", test_multiple_threads_R_and_S);
25 sleep(1);
26 }
27}
28
29int main(int argc, const char *argv[])
30{
31 int i = 0;
32 int ret = 0;
33 pthread_t id1,id2;
34
35 ret = pthread_create(&id1, NULL, set_thread, NULL);
36 if(ret)
37 {
38 printf("Create pthread error!\n");
39 return 1;
40 }
41
42 ret = pthread_create(&id2, NULL, read_thread, NULL);
43 if(ret)
44 {
45 printf("Create pthread error!\n");
46 return 1;
47 }
48
49 pthread_join(id1,NULL);
50 pthread_join(id2,NULL);
51
52 return 0;
53}
直接运行上述代码可能会出现报错对‘pthread_create’未定义的引用
, 可以参考[codeblocks 多线程编程时出现:对pthread_create未定义的引用,解决方法]中的方法进行调试.
如果上述程序运行理想的话, 运行结果应该如下.
写入线程运行到将test变量增加到20之后, 被kill. 读线程正常运行直到主进程结束. (此时需要了解进程线程之间的关系, 以及程序中的线程进程的生命周期.
到此测试结束, 运行成功.