互斥锁有一个明显的缺点就是只有两种状态:锁定和非锁定,而条件变量通过允许线程阻塞和等待另个线程发送信号的方法来弥补互斥锁的不足。条件变量通常和互斥锁一起使用。
条件变量的结构为pthread_cond_t
涉及函数:
pthread_cond_init
pthread_cond_detroy
pthread_cond_wait
pthread_cond_timewait
pthread_cond_broadcast
pthread_cond_signal
简单测试用例为:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 typedef enum{ true=1,false=0 } bool;
5 char buffer[128];
6 bool buffer_has_data = false;
7 pthread_mutex_t mutex;
8 pthread_cond_t cond;
9
10 void write_buffer(char *data)
11 {
12 pthread_mutex_lock(&mutex);
13 if (!buffer_has_data)
14 {
15 sprintf(buffer, "%s", data);
16 buffer_has_data = true;
17 pthread_cond_signal(&cond);
18 }
19 pthread_mutex_unlock(&mutex);
20 }
21 void read_buffer(void)
22 {
23 while (1)
24 {
25 pthread_mutex_lock(&mutex);
26 while (!buffer_has_data)
27 {
28 pthread_cond_wait(&cond, &mutex);
29 }
30 if (buffer_has_data)
31 {
32 printf("Read buffer, data = [%s]\n", buffer);
33 buffer_has_data = false;
34 }
35 pthread_mutex_unlock(&mutex);
36 sleep(1);
37 }
38 }
39
40 int main( int argc, char **argv)
41 {
42 char input[128];
43 pthread_t reader;
44
45 pthread_mutex_init(&mutex, NULL);
46 pthread_cond_init(&cond, NULL);
47 pthread_create(&reader, NULL, (void *)(read_buffer), NULL);
48
49 while (1)
50 {
51 scanf("%s", input);
52 write_buffer(input);
53 }
54 return 0;
55 }
其实就是在互斥锁的基础上增加了条件变量的应用。