Linux下生产者与消费者的线程实现

代码见《现代操作系统》 第3版。

为了显示效果,添加了printf()函数来显示运行效果

 #include<stdio.h>
#include<pthread.h>
#define MAX 20
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = ; void *producer(void *ptr)
{
int i;
for(i = ; i <= MAX; i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer != ) pthread_cond_wait(&condp, &the_mutex);
buffer = i;
printf("%d ", buffer);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit();
} void *consumer(void *ptr)
{
int i;
for(i = ; i < MAX; i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer == )pthread_cond_wait(&condc, &the_mutex);
buffer = ;
printf("%d ", buffer);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit();
} int main(void)
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, );
pthread_cond_init(&condc, );
pthread_cond_init(&condp, );
pthread_create(&con, , consumer, );
pthread_create(&pro, , producer, );
pthread_join(pro, );
pthread_join(con, );
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
}

编译命令

gcc -lpthread -o procro procro.c

运行后的效果如:

Linux下生产者与消费者的线程实现

上一篇:Command: sl (Steam Locomotive)


下一篇:【spoj SUBLEX】 Lexicographical Substring Search