码迷,mamicode.com
首页 > 编程语言 > 详细

linux多线程示例

时间:2014-05-01 06:36:02      阅读:427      评论:0      收藏:0      [点我收藏+]

标签:com   http   style   blog   class   div   img   c   code   java   log   

bubuko.com,布布扣
 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <pthread.h>
 5 
 6 typedef void* (*fun)(void*);
 7 
 8 fun fun1, fun2;
 9 
10 pthread_mutex_t pmu = PTHREAD_MUTEX_INITIALIZER;
11 pthread_cond_t cond;
12 pthread_t pid1, pid2;
13 int flag = 0;
14 int gnum = 0;
15 int gsub = 100;
16 
17 void *  func1(void * para)
18 {
19     int k = (int)para;
20     printf("func1, ******\n");
21     while(gnum<=100)
22     {   
23         pthread_mutex_lock(&pmu);
24         printf("gnum == %d", gnum);
25         while(gnum==50)
26         {   
27             printf("suspend thread1 at gnum==50 !!! \n");
28             pthread_cond_wait(&cond, &pmu);
29             gnum++;
30        }
31         ++gnum;
32         ++flag;
33         ++k;
34         //printf("flag = %d, k = %d\n", flag, k);
35         pthread_mutex_unlock(&pmu);
36         printf("I am func1\n");
37     }
38             pthread_exit((void*)0);
39 
40 }
41 
42 void * func2(void * para)
43 {
44     int f = (int)para;
45     printf("f == %d\n", f);
46     printf("pthread2 start running !\n");
47     void * ret = NULL;
48     while(gsub>=0)
49     {
50         pthread_mutex_lock(&pmu);
51         gsub--;
52         printf("gsub= %d ", gsub);
53         if(gsub == 20)
54         {
55             printf("now gsnb ==20, and send signal\n");
56             pthread_cond_signal(&cond);
57         }
58         ++flag;
59        ++f;
60         printf("flag = %d, f = %d\n", flag, f);
61         pthread_mutex_unlock(&pmu);
62         printf("I am func2 \n");
63     }
64     //pthread_join(pid1, &ret);
65     pthread_exit((void*)0);
66 }
67 
68 int main()
69 {
70     int id = 0;
71     void * ret = NULL;
72     int key = 5;
73 
74     pthread_cond_init(&cond, NULL);  //属性设置NULL默认属性
75     id = pthread_create(&pid1, NULL, func1, (void*)key);
76     if(id != 0)
77     {
78         printf("pthread_create error !\n");
79         exit(0);
80     }
81 
82     if(pthread_create(&pid2, NULL, func2, (void*)key))
83     {
84         printf("pthread_create error ! \n");
85         exit(0);
86     }
87     pthread_join(pid2, &ret);
88     pthread_join(pid1, &ret);
89     pthread_exit((void*)0);
90 }
bubuko.com,布布扣

gcc test_thread.c -lpthread
./a.out

linux多线程示例,布布扣,bubuko.com

linux多线程示例

标签:com   http   style   blog   class   div   img   c   code   java   log   

原文地址:http://www.cnblogs.com/chris-cp/p/3701955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!