码迷,mamicode.com
首页 > 其他好文 > 详细

条件变量和互斥锁

时间:2019-07-26 01:41:28      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:void   using   name   color   passing   互斥锁   nal   error:   变量   

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #include<unistd.h>
 5 #include<pthread.h>
 6 #include<errno.h>
 7 #include<iostream>
 8 using namespace std;
 9 
10 /*提示出租车到达的条件变量*/
11 pthread_cond_t taxiCond = PTHREAD_COND_INITIALIZER;
12 /*同步锁*/
13 pthread_mutex_t taxiMutex = PTHREAD_MUTEX_INITIALIZER;
14 
15 int travelerCount = 0;
16 
17 void *traveler_arrive(void* name) {
18     cout << "Travel:" << (char*)name << "need a taxi now!" << endl;
19     pthread_mutex_lock(&taxiMutex);
20     travelerCount++;
21     pthread_cond_wait(&taxiCond,&taxiMutex);
22     pthread_mutex_unlock(&taxiMutex);
23     cout << "Traveler:" << (char*)name << "now got a taxi!" << endl;
24     pthread_exit((void*)0);
25 }
26 void *taxi_arrive(void *name) {
27     cout << "Taxi:" << (char*)name << "arrives." << endl;
28     while (1) {
29         pthread_mutex_lock(&taxiMutex);
30         if (travelerCount > 0) {
31             pthread_cond_signal(&taxiCond);
32             pthread_mutex_unlock(&taxiMutex);
33             break;
34         }
35         pthread_mutex_unlock(&taxiMutex);
36     }
37     pthread_exit((void*)0);
38 }
39 
40 int main() {
41     pthread_t tids[3];
42     int iRet = pthread_create(&tids[0], NULL, taxi_arrive, (void*)(" Jack "));
43     if (iRet) {
44         printf("pthread_creat error: iRet = %d\n", iRet);
45         return iRet;
46     }
47     printf("Time passing by\n");
48     sleep(1);
49     iRet = pthread_create(&tids[1], NULL, traveler_arrive, (void*)(" Susan "));
50     if (iRet) {
51         printf("pthread_creat error: iRet = %d\n", iRet);
52         return iRet;
53     }
54     printf("Time passing by\n");
55     iRet = pthread_create(&tids[2], NULL, taxi_arrive, (void*)(" Mike "));
56     if (iRet) {
57         printf("pthread_creat error: iRet = %d\n", iRet);
58         return iRet;
59     }
60     printf("Time passing by\n");
61     sleep(1);
62     void *retval;
63     for (int i = 0; i < 3; i++) {
64         iRet = pthread_join(tids[i], &retval);
65         if (iRet) {
66             printf("Join error: iRet = %d\n", iRet);
67             return iRet;
68         }
69         printf("retval = %ld\n", (long)retval);
70     }
71     return 0;
72 }

 

条件变量和互斥锁

标签:void   using   name   color   passing   互斥锁   nal   error:   变量   

原文地址:https://www.cnblogs.com/--lr/p/11247753.html

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