- 系统中有3个线程:生产者、计算者、消费者
- 系统中有2个容量为4的缓冲区:buffer1、buffer2
- 生产者生产'a'、'b'、'c'、‘d'、'e'、'f'、'g'、'h'八个字符,放入到buffer1
- 计算者从buffer1取出字符,将小写字符转换为大写字符,放入到buffer2
- 消费者从buffer2取出字符,将其打印到屏幕上
与多线程最后一个例子相似,再加入
pthread_cond_t wait_empty_buffer1;
pthread_cond_t wait_full_buffer1;
pthread_cond_t wait_empty_buffer2;
pthread_cond_t wait_full_buffer2;
对其进行控制源码如下:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define CAPACITY 4
int buffer1[CAPACITY];
int buffer2[CAPACITY];
int in1;
int out1;
int in2;
int out2;
int buffer_is_empty1()
{
return in1 == out1;
}
int buffer_is_full1()
{
return (in1 + 1) % CAPACITY == out1;
}
int buffer_is_empty2()
{
return in2 == out2;
}
int buffer_is_full2()
{
return (in2 + 1) % CAPACITY == out2;
}
int get_item1()
{
int item;
item = buffer1[out1];
out1 = (out1 + 1) % CAPACITY;
return item;
}
void put_item1(int item)
{
buffer1[in1] = item;
in1 = (in1 + 1) % CAPACITY;
}
int get_item2()
{
int item;
item = buffer2[out2];
out2 = (out2 + 1) % CAPACITY;
return item;
}
void put_item2(int item)
{
buffer2[in2] = item;
in2 = (in2 + 1) % CAPACITY;
}
pthread_mutex_t mutex;
pthread_cond_t wait_empty_buffer1;
pthread_cond_t wait_full_buffer1;
pthread_cond_t wait_empty_buffer2;
pthread_cond_t wait_full_buffer2;
#define ITEM_COUNT (CAPACITY * 2)
void *consume(void *arg)
{
int i;
int item;
for (i = 0; i < ITEM_COUNT; i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_empty2())
pthread_cond_wait(&wait_full_buffer2, &mutex);
item = get_item2();
printf("%c ",item);
pthread_cond_signal(&wait_empty_buffer2);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *counter(void *arg)
{
int i;
int item;
for (i = 0; i < ITEM_COUNT; i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_empty1())
pthread_cond_wait(&wait_full_buffer1, &mutex);
item = get_item1();
// printf("counter1:%c ",item);
while (buffer_is_full2())
pthread_cond_wait(&wait_empty_buffer2, &mutex);
item = item - 32;
// printf("counter2:%c ",item);
put_item2(item);
pthread_cond_signal(&wait_full_buffer2);
pthread_cond_signal(&wait_empty_buffer1);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *produce(void *arg)
{
int i;
int item;
for (i = 0; i < ITEM_COUNT; i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_full1())
pthread_cond_wait(&wait_empty_buffer1, &mutex);
item = 'a' + i;
// printf("produce:%c \n",item);
put_item1(item);
pthread_cond_signal(&wait_full_buffer1);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t consumer_tid;
pthread_t counter_tid;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&wait_empty_buffer1, NULL);
pthread_cond_init(&wait_full_buffer1, NULL);
pthread_cond_init(&wait_empty_buffer2, NULL);
pthread_cond_init(&wait_full_buffer2, NULL);
pthread_create(&counter_tid, NULL, counter, NULL);
pthread_create(&consumer_tid, NULL, consume, NULL);
produce(NULL);
pthread_join(counter_tid, NULL);
pthread_join(consumer_tid, NULL);
return 0;
}
结果: