关于条件变量

最近打算在写一个网络库,涉及到对mutex、condition的封装,再次使用Linux提供的接口,发现一个问题,使用condition的时候需要配合一个mutex来使用。

上面是关于pthread_cond_wait的man手册说明,意思就是再调用pthread_cond_wait之前需要把mutex上锁,pthread_cond_wait会自动解锁,然后等待条件变量被signal,执行线程会被挂起并不会消耗任何CPU时间,知道条件变量被signal。在返回到调用线程之前,pthread_cond_wait会重新获取锁(如果获取不到锁,会阻塞)。

我想要测试就是最后一点,如果在返回的时候获取不到锁,会不会阻塞,以及想知道为什么需要与一个mutex配合使用。

测试代码:

 1 /*
 2 * 测试pthread_cond_wait
 3 */
 4 #include <unistd.h>
 5 #include <pthread.h>
 6 
 7 #include <stdio.h>
 8 
 9 pthread_mutex_t mutex;
10 pthread_cond_t cond;
11 
12 void* mutex_func(void *arg)
13 {
14     // wait cond_func get the lock
15     printf("lock after 5s
");
16     sleep(5);
17     pthread_mutex_lock(&mutex);
18 
19     pthread_cond_signal(&cond);
20 
21     printf("unlock after 5s
");
22     sleep(5);
23     pthread_mutex_unlock(&mutex);
24 }
25 
26 void* cond_func(void *arg)
27 {
28     // lock
29     pthread_mutex_lock(&mutex);
30 
31     pthread_cond_wait(&cond, &mutex); // unlock and block
32     printf("get signal
");
33 
34     pthread_mutex_unlock(&mutex);
35     // acquire lock, will block
36     printf("cond_func
");
37 }
38 
39 int main(void)
40 {
41     pthread_mutex_init(&mutex, NULL);
42     pthread_cond_init(&cond, NULL);
43 
44     pthread_t pid1, pid2;
45     pthread_create(&pid1, NULL, mutex_func, NULL);
46     pthread_create(&pid2, NULL, cond_func, NULL);
47 
48     pthread_join(pid1, NULL);
49     pthread_join(pid2, NULL);
50 
51     return 0;
52 }

输出结果:

结论:

根据输出结果可以知道,确实是它需要的mutex释放之后才从pthread_cond_wait返回的。此处可以推测(需要看源码验证)pthread_cond_wait是去查看某一个条件是否为真来决定是否返回的(那么就涉及到了race condition),所以需要使用mutex来保护。

源码验证:

原文地址:https://www.cnblogs.com/lit10050528/p/7580422.html