使用多线程程序模拟实现单生产者/多消费者问题 (Linux 线程锁实践)

线程锁应用

要求“生产者”随机产生一个整数,“消费者 1”将这个整数加 1 后输出,“消 费者 2”将这个整数加 2 后输出,“消费者 3”将这个整数加 3 后输出,“消 费者 4”将这个整数加 4 后输出。当程序接收到键盘输入“q”或“Q”时退 出。

思路

​ 简单的加锁和信号量操作。

代码部分

#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;//number lock
pthread_mutex_t mcnt=PTHREAD_MUTEX_INITIALIZER;
int number=0;
int cnt=1;
int shop=0;
sem_t check[5];
sem_t empty;
void* sonthread(void *arg){
        pthread_mutex_lock(&mcnt);
        int now=cnt;cnt=cnt+1;
        pthread_mutex_unlock(&mcnt);
        while(1){
                sem_wait(&check[now]);
                pthread_mutex_lock(&mtx);
                printf("%d thread add number result is :%d
",now,number+now);
                pthread_mutex_unlock(&mtx);
                sem_post(&empty);
                sleep((double)(rand()%4)*1000/1000.0);
        }
}
void* fatherthread(void *arg){
        while(1){
                pthread_mutex_lock(&mtx);
                number=rand();
                pthread_mutex_unlock(&mtx);
                printf("producer produce a number :%d
",number);
                int i=1;
                for(i=1;i<=4;i++)sem_post(&check[i]);
                sem_wait(&empty);
                sem_wait(&empty);
                sem_wait(&empty);
                sem_wait(&empty);
                printf("product has ran out
");
                sleep(2);
        }
}
int main(){
        sem_init(&empty,0,0);
        pthread_mutex_init(&mtx,PTHREAD_MUTEX_TIMED_NP);
        pthread_mutex_init(&mcnt,NULL);
        pthread_t p_id[5];
        int i=1;
        for(i=1;i<=4;i++){
                sem_init(&check[i],0,0);
                pthread_create(&p_id[i],NULL,sonthread,NULL);
        }
        pthread_create(&p_id[0],NULL,fatherthread,NULL);
        signal(SIGINT,SIG_IGN);
        system("stty -icanon -echo");
        char c;
        while(c=getchar()){
                if(c=='Q'||c=='q'){
                        system("stty echo");
                        exit(0);
                }
        }
        return 0;
}

原文地址:https://www.cnblogs.com/greenpepper/p/14177375.html