生产者消费者,多线程问题

从上一个小测试当中,我们会发现线程之间存在争夺问题,所以在这里用上了信号锁

#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_SIZE 5
struct data_struct{
    time_t the_time;
    pthread_t pid;
    int order;
}Pro[MAX_SIZE];
sem_t sem1,sem2;//signal
pthread_mutex_t mutex1,mutex2;

int in = 0,out = 0;
void producethread(void* arg);
void customerthread(void* arg);

int main(int argc,const char* argv[])
{
    pthread_t pro1,pro2;
    pthread_t cus1,cus2;
    
    sem_init(&sem1,0,4);
    sem_init(&sem2,0,0);

    pthread_mutex_init(&mutex1,NULL);
    pthread_mutex_init(&mutex2,NULL);
    
    pthread_create(&pro1,NULL,(void*)producethread,NULL);
    pthread_create(&pro2,NULL,(void*)producethread,NULL);
    pthread_create(&cus1,NULL,(void*)customerthread,NULL);
    pthread_create(&cus2,NULL,(void*)customerthread,NULL);
    
    //pthread_mutex_destory(&mutex1);
    //pthread_mutex_destory(&mutex2);
    
    pthread_join(pro1,NULL);
    pthread_join(pro2,NULL);
    pthread_join(cus1,NULL);
    pthread_join(cus2,NULL);

    exit(EXIT_SUCCESS);
}

void producethread(void* arg)
{
    int i;
    for(i=0;i<10;i++)
    {
        //sem_wait(&sem1);//wrire   信号量通知写 说明消费者以及读完了
        pthread_mutex_lock(&mutex1);
        Pro[in%MAX_SIZE].pid = pthread_self();
        Pro[in%MAX_SIZE].order = i;
        time(&Pro[in%MAX_SIZE].the_time);
        in++;
        //sem_post(&sem2);
        pthread_mutex_unlock(&mutex1);
        sleep(2);
    }
}
void customerthread(void* arg)
{
    int counter=0;
    while(1){
        if(counter == 10)
        {
            break;
        }
        //sem_wait(&sem2);
        pthread_mutex_lock(&mutex2);
        if(out%2 == 0)
        {
            printf("customer1:");
        }
        else{
            printf("customer2:");
        }
        printf("order=%2d   thread_id=%5d   time:%s",(int)Pro[out%MAX_SIZE].order,(int)Pro[out%MAX_SIZE].pid,ctime(&Pro[out%MAX_SIZE].the_time));
        out++;
        //sem_post(&sem1);
        pthread_mutex_unlock(&mutex2);
        sleep(3);
        counter++;
    }
}
刚开始写的时候没有加入信号量来进行交互,得到了以下的结果

发现并不是符合我们预期的输出,会出现数据杂乱,错读重复的现象,说明写入和读出是由CPU随机调度的.

所以在这里加上了sem_t  信号量,来进行线程间的互相通知,消费者线程利用同一个锁互斥,不会造成混乱,同时通知生产者是否要生成数据,生产者线程也通过另一个锁互斥,不会不按顺序生产,这样的话就能够做到生产完成之后发送信号,消费者进行消费.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值