信号量

信号量是加强版的互斥锁,允许多个线程访问共享资源
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给算法爸爸上香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值