#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
// 初始化互斥量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 条件变量
pthread_cond_t cond1;
// 资源
int source;
// 生产者
void *producer(void *v)
{
while(1)
{
usleep(100000*(rand()%10+1));
pthread_mutex_lock(&mutex);
source += 2;
pthread_mutex_unlock(&mutex);
// 广播
pthread_cond_broadcast(&cond1);
}
}
// 消费者
void *customer (void *v)
{
long num = (long)v;
while(1)
{
// 为什么要有循环
// 因为当线程被唤醒的时候,有可能条件还是不满足的,所以还需要判断一次
// 1、当等待的时候,会自动解锁
// 2、当被唤醒的时候,会和其他线程一起抢锁
usleep(100000*(rand()%10+1));
pthread_mutex_lock(&mutex);
while (source <= 0)
{
pthread_cond_wait(&cond1, &mutex);
}
source--;
printf ("%ld消费者消费,剩余个数%d\n", num, source);
pthread_mutex_unlock(&mutex);
}
}
// 生产者与消费者
int main()
{
srand((unsigned int)time(NULL));
pthread_t thread;
long i;
for (i = 0; i < 4; i++)
{
pthread_create(&thread, NULL, customer, (void *)(i+1));
pthread_detach(thread);
}
pthread_create(&thread, NULL, producer, NULL);
pthread_detach(thread);
// pthread_cond_init(pthread_cond_t *cond,const pthread_condattr_t *attr);
// 条件变量的初始化
pthread_cond_init(&cond1, NULL);
pthread_exit(NULL);
return 0;
}
线程——条件变量
猜你喜欢
转载自blog.csdn.net/ypjsdtd/article/details/86406051
今日推荐
周排行