使用信号量的生产者—消费者问题

《现代操作系统》 第二章 进程和线程


多线程编程真的很麻烦。。。



#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>


#define N 100//缓冲区大小

//三个信号量
sem_t mutex;//控制对临界区打访问
sem_t empty;//缓冲区的空槽数目
sem_t full;//缓冲区的满槽数目

int buffer[N];//缓冲区

int front=0;//缓冲区队列头
int rear=1;//缓冲区队列尾

void *producer (void * tid)
{
    int item=0;//要存放的数字

    while(item<=100)
    {
        item++;//产生缓冲区数据
        sem_wait(&empty);//将空槽数目建一
        sem_wait(&mutex);//进入临界区


        buffer[rear]=item;//缓冲区中放入数据
        rear=(rear+1)%N;//队尾+1

        printf("            producer %d\n",item);


        sem_post(&mutex);//离开临界区
        sem_post(&full);//将满槽数目加一

    }

}

void *consumer(void * tid)
{
    while(true)
    {
        sem_wait(&full);
        sem_wait(&mutex);

        front=(front+1)%N;
        printf("consumer %d\n",buffer[front]);



        sem_post(&mutex);
        sem_post(&empty);
    }
}


int main()
{
    sem_init(&mutex,0,1);//初始化信号量,赋值为1
    sem_init(&empty,0,N);
    sem_init(&full,0,0);

    pthread_t pro,con;//线程号

    pthread_create(&con,0,consumer,NULL);//创建线程
    pthread_create(&pro,0,producer,NULL);
    pthread_join(pro,0);//如果没有pthread_join;主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了
    pthread_join(con,0);//加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行
    //pthread_join函数会让主线程阻塞,直到所有线程都已经退出

    sem_destroy(&full);//销毁
    sem_destroy(&empty);
    sem_destroy(&mutex);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值