记录型信号量解决生产者消费者问题

本文详细描述了一个使用C语言实现的生产者消费者模型,通过互斥信号量mutex、empty和full来同步多线程对缓冲区的操作,展示了并发控制在处理共享资源时的应用。
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdio.h>

#define BUFSIZE 5
#define pNUM 5  //生产者数量 
#define cNUM 5  //消费者数量 
int in=0 , out=0; //生产者指针和消费者指针 
//pthread_mutex_t ch_mutex;
sem_t mutex , empty , full; //互斥信号量-缓冲区互斥使用,empty缓冲区中空缓冲区的数量 
char nextp;
char buff[BUFSIZE]={'*','*','*','*','*'};
 
void printfBuff()
{
    int i;
    for(i=0;i<BUFSIZE;i++) printf("%c",buff[i]);
    printf("\n");
}
//生产者
void *producer(void *arg){
     int i = 0;
     while(i<3){        //每个生产者最多可以对缓冲区操作3次
		nextp = 'p';
		sem_wait(&empty); //申请一个空缓冲区 
		sem_wait(&mutex);
		buff[in] = nextp;       
		in = (in+1) % BUFSIZE; 
        i++;
        printf("生产者%ld生产一个p\t",pthread_self());
        printfBuff();
		sem_post(&mutex);
		sem_post(&full);                  
	}
}
//消费者
void *consumer(void *arg){
       int i = 0;
       while(i<3){   //每个消费者最多可以对缓冲区操作3次         
	      sem_wait(&full);
		  sem_wait(&mutex);
		  nextp = buff[out];
          buff[out] = '*';              
          out = (out+1) % BUFSIZE;            
          i++;
          printf("消费者%ld取出一个p\t",pthread_self()); 
          printfBuff();
		  sem_post(&mutex);
		  sem_post(&empty);            
       }	
}
int main()
{
      printf("BUFSIZE = 5\t");
      printfBuff();
	  sem_init(&mutex,0,1);
	  sem_init(&empty,0,BUFSIZE);
	  sem_init(&full,0,0);
	
	  pthread_t ptid[pNUM]; //5个生产者 
	  pthread_t ctid[cNUM]; //5个消费者 
	  int i1,j1,i2,j2;
	  for(i1=0;i1<pNUM;i1++){
		  pthread_create(&ptid[i1],NULL,producer,&i1);
	  }
	
	  for(i2=0;i2<5;i2++){
		  pthread_create(&ctid[i2],NULL,consumer,&i2);
	  }
      for(i1=0;i1<pNUM;i1++) pthread_join(ptid[i1],NULL);
      for(i2=0;i2<cNUM;i2++) pthread_join(ctid[i2],NULL);

      sem_destroy(&mutex);
      sem_destroy(&empty);
      sem_destroy(&full);
}

运行结果

84d5ca1e4d944e2d96ad9817764a58ae.png

 

下面是一个使用 C 代码结合 POSIX 信号量实现记录型信号量解决生产者 - 消费者问题的示例。该示例使用了 POSIX 线程库(`pthread`)和信号量库(`semaphore.h`)。 ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #define N 5 // 缓冲区大小 // 缓冲区 int buffer[N]; int in = 0; int out = 0; // 信号量 sem_t mutex; // 用于互斥访问缓冲区 sem_t empty; // 表示缓冲区中空槽的数量 sem_t full; // 表示缓冲区中满槽的数量 // 生产者线程函数 void *producer(void *arg) { int item; for (int i = 0; i < 10; i++) { item = rand() % 100; // 生成一个随机数作为要生产的物品 // 判断缓冲池中是否仍有空闲的缓冲区 sem_wait(&empty); // 判断是否可以进入临界区(操作缓冲池) sem_wait(&mutex); // 向缓冲池中投放消息 buffer[in] = item; printf("Produced %d at position %d\n", item, in); // 移动入队指针 in = (in + 1) % N; // 退出临界区,允许别的进程操作缓冲池 sem_post(&mutex); // 缓冲池中数量的增加,可以唤醒等待的消费者进程 sem_post(&full); } pthread_exit(NULL); } // 消费者线程函数 void *consumer(void *arg) { int item; for (int i = 0; i < 10; i++) { // 判断缓冲池中是否有非空的缓冲区(消息) sem_wait(&full); // 判断是否可以进入临界区(操作缓冲池) sem_wait(&mutex); // 从缓冲池中取出消息 item = buffer[out]; printf("Consumed %d from position %d\n", item, out); // 移动出队指针 out = (out + 1) % N; // 退出临界区,允许别的进程操作缓冲池 sem_post(&mutex); // 缓冲池中空缓冲区数量加1,可以唤醒等待的生产者进程 sem_post(&empty); } pthread_exit(NULL); } int main() { pthread_t producer_thread, consumer_thread; // 初始化信号量 sem_init(&mutex, 0, 1); sem_init(&empty, 0, N); sem_init(&full, 0, 0); // 创建生产者消费者线程 pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); // 等待线程结束 pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); // 销毁信号量 sem_destroy(&mutex); sem_destroy(&empty); sem_destroy(&full); return 0; } ``` ### 代码解释 1. **信号量初始化**:使用 `sem_init` 函数初始化三个信号量:`mutex` 初始化为 1 用于互斥访问缓冲区,`empty` 初始化为 `N` 表示缓冲区初始时全为空,`full` 初始化为 0 表示缓冲区初始时没有满槽。 2. **生产者线程**:在 `producer` 函数中,生产者生成一个随机数作为要生产的物品。首先通过 `sem_wait(&empty)` 检查缓冲区是否有空闲槽,然后通过 `sem_wait(&mutex)` 进入临界区,将物品放入缓冲区,更新入队指针,最后通过 `sem_post(&mutex)` 退出临界区,并通过 `sem_post(&full)` 通知消费者有新的物品可消费。 3. **消费者线程**:在 `consumer` 函数中,消费者首先通过 `sem_wait(&full)` 检查缓冲区是否有物品,然后通过 `sem_wait(&mutex)` 进入临界区,从缓冲区取出物品,更新出队指针,最后通过 `sem_post(&mutex)` 退出临界区,并通过 `sem_post(&empty)` 通知生产者有新的空闲槽。 4. **主线程**:创建生产者消费者线程,并等待它们结束。最后销毁信号量。 ### 编译和运行 要编译这个程序,可以使用以下命令: ```sh gcc -o producer_consumer producer_consumer.c -lpthread ``` 运行程序: ```sh ./producer_consumer ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值