/*
*生产者消费者问题的多线程互斥控制,源程序出自《Linux网络编程》
*/
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
void *producter_f(void *arg);
void *consumer_f(void *arg);
int buffer_has_item = 0; /*设置缓存数量*/
pthread_mutex_t mutex; /*设置互斥*/
int running = 1;
int main (void)
{
pthread_t consumer_t; /*线程参数*/
pthread_t producter_t;
/*不知道这句为什么不给我变蓝色,初始化互斥*/
pthread_mutex_init(&mutex, NULL);
/*创建线程*/
pthread_create(&producter_t, NULL, (void *)producter_f, NULL);
pthread_create(&consumer_t, NULL, (void *)consumer_f, NULL);
usleep(1);
running = 0;
/*等待线程退出,一个线程不能够被多个线程等待*/
pthread_join(consumer_t, NULL);
pthread_join(producter_t, NULL);
/*销毁互斥*/
pthread_mutex_destroy(&mutex);
return 0;
}
void *producter_f(void *arg)
{
while (running)
{
pthread_mutex_lock(&mutex); /*加锁,进入互斥区*/
buffer_has_item++;
printf("product ,num:%d\n", buffer_has_item);
pthread_mutex_unlock(&mutex); /*解锁,离开互斥区*/
}
}
void *consumer_f(void *arg)
{
while (running)
{
pthread_mutex_lock(&mutex);
buffer_has_item--;
printf("consumer,num:%d\n",buffer_has_item);
pthread_mutex_unlock(&mutex);
}
}
|