信号量:进化版的互斥锁(1–N)
主要应用函数:
(1)sem_init
(2)sem_destroy;
(3)sem_wait
(4)sem_trywait;
(5)sem_timewait;
(6)sem_post;
sem_wait:相当于pthread_mutex_lock,(1)信号量>0时–;(2)信号量=0时,阻塞;
sem_post:相当于pthread_mutex_unloxk;(1)信号量++,唤醒因此信号量而阻塞的线程;
区别条件变量实现的生产者消费者模型,信号量可以同时多个消费者同时消费;
生产者–消费者模型的实现
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#define NUM 5
int queue[NUM];//队列表示共享资源的进出
int front=0;
int tail=0;
sem_t blank,star;
void *produce(void *arg)
{
while(1)
{
sem_wait(&blank);//等待剩余空间
queue[tail]=rand()%100+1; //给共享区队列中生产产品;
printf("------procude %d\n",queue[tail]);
tail=(tail+1)%NUM;//循环队列
sem_post(&star);//star+1;
sleep(rand()%3);
}
pthread_exit(NULL);
}
void *consume(void *arg)
{
while(1)
{
sem_wait(&star);//等待star的产出
printf("------consume %d\n",queue[front]);
queue[front]=0;//消费掉一个star
front=(front+1)%NUM;
sem_post(&blank);
sleep(rand()%3);
}
pthread_exit(NULL);
}
int main()
{
sem_init(&blank,0,NUM);//参数二0代表线程间共享pshared,参数三代表信号量的大小
sem_init(&star,0,0);
pthread_t ptid,ctid;
pthread_create(&ptid,NULL,produce,NULL);
pthread_create(&ctid,NULL,consume,NULL);
pthread_join(ptid,NULL);
pthread_join(ctid,NULL);
sem_destroy(&blank);
sem_destroy(&star);
exit(1);
}
结果分析:
------procude 84
------consume 84
------procude 16
------consume 16
------procude 87
------consume 87
------procude 22
------consume 22
------procude 91
------consume 91
------procude 27
------procude 27
------consume 27
------procude 12
------consume 27
------consume 12
------procude 83
------consume 83
------procude 24
------consume 24
------procude 30
------consume 30
------procude 59
------consume 59
只有有产品才能消费,结果符和预期;