标签:线程同步与互斥
1 #include<stdio.h> 2 #include<pthread.h> 3 #include<stdlib.h> 4 5 static int i = 1; 6 pthread_mutex_t lock; 7 pthread_mutex_t lock1; 8 pthread_cond_t cond; 9 typedef struct node 10 { 11 int _data; 12 struct node* _next; 13 }node; 14 15 struct node *head; 16 node* buy_node(node* head,int data) 17 { 18 node* list = malloc(sizeof(node*)); 19 list->_data = data; 20 list->_next = NULL; 21 return list; 22 } 23 void init(node** head) 24 { 25 *head = buy_node(*head,0); 26 } 27 void push(node* head,int data) 28 { 29 node* tmp = buy_node(head,data); 30 tmp->_next = head->_next; 31 head->_next = tmp; 32 } 33 int pop(node* head,int* arr) 34 { 35 if(head->_next == NULL) 36 { 37 *arr = -1; 38 return -1; 39 } 40 41 //node* tmp = head->_next; 42 //head->_next = tmp->_next; 43 //*arr = tmp->_data; 44 45 node* tmp = head; 46 node* prev = NULL; 47 while(tmp->_next) 48 { 49 prev = tmp; 50 tmp = tmp->_next; 51 } 52 prev->_next = NULL; 53 *arr = tmp->_data; 54 free(tmp); 55 tmp = NULL; 56 return 0; 57 } 58 59 void *product(void *arg) 60 { 61 pthread_mutex_lock(&lock1); 62 //int i = 1; 63 while(1) 64 { 65 pthread_mutex_lock(&lock); 66 printf("product %d:%d\n",(int)arg,i); 67 push(head,i++); 68 pthread_mutex_unlock(&lock); 69 pthread_cond_signal(&cond); 70 sleep(1); 71 } 72 pthread_mutex_unlock(&lock1); 73 } 74 void *consumer(void *arg) 75 { 76 pthread_mutex_unlock(&lock1); 77 int buf; 78 while(1) 79 { 80 pthread_mutex_lock(&lock); 81 while(pop(head,&buf)==-1) 82 { 83 printf("consumer wait... product done...\n"); 84 pthread_cond_wait(&cond,&lock); 85 } 86 pthread_mutex_unlock(&lock); 87 printf("consumer %d:%d\n",(int)arg,buf); 88 sleep(1); 89 } 90 pthread_mutex_unlock(&lock1); 91 } 92 int main() 93 { 94 init(&head); 95 pthread_mutex_init(&lock,NULL); 96 pthread_mutex_init(&lock1,NULL); 97 pthread_cond_init(&cond,NULL); 98 pthread_t tid1,tid2,tid3,tid4; 99 pthread_create(&tid1,NULL,product,(void*)1); 100 pthread_create(&tid2,NULL,consumer,(void*)1); 101 pthread_create(&tid3,NULL,product,(void*)2); 102 pthread_create(&tid4,NULL,consumer,(void*)2); 103 104 pthread_join(tid1,NULL); 105 pthread_join(tid2,NULL); 106 pthread_join(tid3,NULL); 107 pthread_join(tid4,NULL); 108 pthread_mutex_destroy(&lock); 109 pthread_mutex_destroy(&lock1); 110 pthread_cond_destroy(&cond); 111 return 0; 112 } [fbl@localhost cond]$ ./my_cond consumer wait... product done... product:1 consumer:1 consumer wait... product done... product:2 consumer:2 consumer wait... product done... [fbl@localhost cond]$ ./my_cond consumer wait... product done... product 2:1 consumer 2:1 product 1:2 consumer 1:2 consumer wait... product done... consumer wait... product done... product 2:3 consumer 2:3 product 1:4 consumer 1:4 consumer wait... product done... consumer wait... product done... product 2:5 consumer 2:5 product 1:6 consumer 1:6 consumer wait... product done... consumer wait... product done... product 2:7 consumer 2:7
标签:线程同步与互斥
原文地址:http://fengbaoli.blog.51cto.com/10538178/1766352