练习Linux多线程环境下的第一个例程:
存在三个不同的线程:
线程1只输出----------。
线程2只输出偶数。
线程3只输出奇数。
结果输出:
-----------
0
-----------
1
-----------
2
-----------
3
一直到:
-----------
999
-----------
1000
定义结构体:struct oddevenzero_t
struct oddevenzero_t
8 {
9 pthread_mutex_t mu_odd;
10 pthread_mutex_t mu_even;
11 pthread_mutex_t mu_zero;
12 int n;
13 int num;
14 };
15
16 struct oddevenzero_t *test;
线程和互斥锁创建:
int main()
64 {
65 pthread_t tid;
66 int ret, i = 0;
67 test = (struct oddevenzero_t*)malloc(sizeof(struct oddevenzero_t));
68 pthread_mutex_init(&test->mu_odd, NULL);
69 pthread_mutex_init(&test->mu_zero, NULL);
70 pthread_mutex_init(&test->mu_even, NULL);
71 pthread_mutex_lock(&test->mu_odd);
72 pthread_mutex_lock(&test->mu_even);
73 pthread_mutex_unlock(&test->mu_zero);
74 test->n = 1000 + 1;
75 test->num = 0;
76 for(i = 1; i <= 3; i++)
77 {
78 ret = pthread_create(&tid, NULL, task, (void*)i);
80 pthread_detach(tid);
81
82 if(ret != 0)
83 {
84 fprintf(stderr, "creat thread err:%s\n", strerror(ret));
85 exit(1);
86 }
87 }
89 sleep(1);
90 return 0;
91 }
线程函数:
19 void *task(void *arg)
20 {
21 if((int)arg == 1)
22 {
24 while(1){
25 pthread_mutex_lock(&test->mu_zero);
26 if(test->num%2 == 0){
27 printf("-----------\n");
28 pthread_mutex_unlock(&test->mu_odd);
29 }
30 else{
31 printf("-----------\n");
32 pthread_mutex_unlock(&test->mu_even);
33 }
34 }
35 }
36 if((int)arg == 2)
37 {
39 while(1){
40 pthread_mutex_lock(&test->mu_odd);
41 printf("%d\n", test->num);
42 test->num ++;
43 if(test->num < test->n){
44 pthread_mutex_unlock(&test->mu_zero);
45 }
46 }
47 }
48 if((int)arg == 3)
49 {
51 while(1){
52 pthread_mutex_lock(&test->mu_even);
53 printf("%d\n", test->num);
54 test->num ++;
55 if(test->num < test->n){
56 pthread_mutex_unlock(&test->mu_zero);
57 }
58 }
59 }
60 return NULL;
61 }