| 这3点很简单嘛!!!不就是调用pthread_create创建线程。代码如下: 
#include<stdio.h>#include<stdlib.h>
 #include<pthread.h>
 #include<errno.h>
 #include<unistd.h>
 int g_Flag=0;
 void* thread1(void*);
 void* thread2(void*);
 /*
 * when program is started, a single thread is created, called the initial thread or main thread.
 * Additional threads are created by pthread_create.
 * So we just need to create two thread in main().
 */
 int main(int argc, char** argv)
 {
 printf("enter mainn");
 pthread_t tid1, tid2;
 int rc1=0, rc2=0;
 rc2 = pthread_create(&tid2, NULL, thread2, NULL);
 if(rc2 != 0)
 printf("%s: %dn",__func__, strerror(rc2));
 rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
 if(rc1 != 0)
 printf("%s: %dn",__func__, strerror(rc1));
 printf("leave mainn");
 exit(0);
 }
 /*
 * thread1() will be execute by thread1, after pthread_create()
 * it will set g_Flag = 1;
 */
 void* thread1(void* arg)
 {
 printf("enter thread1n");
 printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
 g_Flag = 1;
 printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
 printf("leave thread1n");
 pthread_exit(0);
 }
 /*
 * thread2() will be execute by thread2, after pthread_create()
 * it will set g_Flag = 2;
 */
 void* thread2(void* arg)
 {
 printf("enter thread2n");
 printf("this is thread2, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
 g_Flag = 2;
 printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
 printf("leave thread2n");
 pthread_exit(0);
 }
 这样就完成了1)、2)、3)这三点要求。编译执行得如下结果: netsky@ubuntu:~/workspace/pthead_test$ gcc -lpthread test.c 如果程序中使用到了pthread库中的函数,除了要#include<pthread.h>,在编译的时候还有加上-lpthread 选项。 netsky@ubuntu:~/workspace/pthead_test$ ./a.out
 enter main
 enter thread2
 this is thread2, g_Flag: 0, thread id is 3079588720
 this is thread1, g_Flag: 2, thread id is 3079588720
 leave thread2
 leave main
 enter thread1
 this is thread1, g_Flag: 2, thread id is 3071196016
 this is thread1, g_Flag: 1, thread id is 3071196016
 leave thread1
 但是运行结果不一定是上面的,还有可能是:
 netsky@ubuntu:~/workspace/pthead_test$ ./a.out enter main
 leave main
 enter thread1
 this is thread1, g_Flag: 0, thread id is 3069176688
 this is thread1, g_Flag: 1, thread id is 3069176688
 leave thread1
 或者是: netsky@ubuntu:~/workspace/pthead_test$ ./a.out enter main
 leave main
 等等。这也很好理解因为,这取决于主线程main函数何时终止,线程thread1、thread2是否能够来得急执行它们的函数。这也是多线程编程时要注意的问题,因为有可能一个线程会影响到整个进程中的所有其它线程!如果我们在main函数退出前,sleep()一段时间,就可以保证thread1、thread2来得及执行。
 (编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |