pthread 条件变量(condition variable) 的基本用法

用法在我翻译的一篇问答里已经说得比较清楚了,这里只是给出我写的一个示例程序。文章
地址在这里

例子中有两个线程为消费者,一个线程为生产者。在那篇问答中回答者给出了一个模型,但
人尝试的时候发现将获取和释放互斥量放在循环外会有问题,参考网上其他一些程序经过思
考后将其放在了循环内,程序如下:

例子程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

int loop = 5;
int count = 3;
int has_work = 1;
pthread_mutex_t lock;
pthread_cond_t cond;
void *increase(void *arg);
void *decrease(void *arg);

int main(int argc, char *argv[])
{
pthread_t thread_dec1, thread_dec2, thread_inc;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
int has_work = 1;

pthread_create(&thread_inc, 0, increase, 0);
pthread_create(&thread_dec1, 0, decrease, 0);
pthread_create(&thread_dec2, 0, decrease, 0);

pthread_join(thread_inc, 0);
pthread_join(thread_dec1, 0);
pthread_join(thread_dec2, 0);

pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
return 0;
}

void *increase(void *arg)
{
while (1) {
sleep(1);
pthread_mutex_lock(&lock);

count += 3;
printf("thread [%#lx] increased count[%d]\n", pthread_self(), count);
if (--loop <= 0) {
has_work = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
break;
}

pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
}
/* printf("increase exited\n"); */
return 0;
}

void *decrease(void *arg)
{
while (has_work) {
/* printf("decrease into loop\n"); */
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
if (count > 0) {
--count;
printf("thread [%ld] decreased count[%d]\n", pthread_self(), count);
}
pthread_mutex_unlock(&lock);
}
/* printf("decrease exited\n"); */
return 0;
}

References

条件变量pthread_cond_t怎么用
Linux多线程编程详细解析—-条件变量 pthread_cond_t

0%