信号量是加强版的互斥锁,允许多个线程访问共享资源
int sem_init(sem_t *sem,int pshared,unsigned int value);
sem 定义的信号量,传出
pshared 0代表线程信号量,非0代表进程信号量
value 定义信号量的个数
摧毁信号量
int sem_destroy(sem_t *sem);
申请信号量
int sem_wait(sem_t *sem); 当信号量为0时阻塞
释放信号量
int sem_post(sem_t *sem);
sem_product.c
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
sem_t blank,xfull;
#denfine _SEM_CNT_ 5
int beginnum=100;
typedef struct _ProdInfo{
int num;
struct _ProdInfo *next;
}ProdInfo;
int queue[_SEM_CNT_];
int beginnnum=100;
void* thr_producter(void *arg)
{
int i=0;
while(1){
sem_wait(&blank); //申请资源
printf("----%s----self--%lu----num----%d\n",__FUNCTION__,pthread_self(),beginnum);
queue[(i++)%_SEM_CNT_]=beginnum++;
sem_post(&xfull);
sleep(rand()%3);
}
return NULL;
}
void* thr_customer(void *arg)
{
int i=0,num=0;
while(1){
sem_wait(xfull);
num=queue[(i++)%_SEM_CNT_];
printf("----%s----self--%lu----num----%d\n",__FUNCTION__,pthread_self(),num);
sem_post(&blank);
sleep(rand()%3);
}
return NULL;
}
int main()
{
sem_init(&blank,0,_SEM_CNT_);
sem_init(&xfull,0,0); //消费者初始化时默认没有产品
pthread_t tid[2];
pthread_create(&tid[0],NULLL,thr_producter,NULL);
pthread_create(&tid[1],NULLL,thr_customer,NULL);
pthread_join(tid[0],NULL);
pthread_join(tid[1],NULL);
sem_destroy(&blank);
sem_destroy(&xfull);
return 0;
}