条件变量和互斥锁

Posted --lr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了条件变量和互斥锁相关的知识,希望对你有一定的参考价值。

 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 

 

以上是关于条件变量和互斥锁的主要内容,如果未能解决你的问题,请参考以下文章

转载同步和互斥的POSIX支持(互斥锁,条件变量,自旋锁)

Go36-27,28-条件变量

信号量,互斥锁,读写锁和条件变量的区别

提升进程间共享互斥锁和提升共享互斥锁的进程间条件变量

Linux下的互斥锁和条件变量

互斥锁自旋锁读写锁和条件变量