c++多线程实现生产者消费者

生产和消费思路:

生产时先扫描一遍buffer找到第一个为0(即没有产品)的位置,生产一个产品,并把产品编号(110循环)存在这里。

消费时先扫描一遍buffer找到第一个不为1(即有产品)的位置,消费一个产品,并使此时位置存的数0(即没有产品)

结果示意图:

 

Producer/consume:表示生产者或者消费者生产或消费的产品的位置以及产品号。

如:Produce buffer[0]=1  buffer[0]表示缓冲区第一个位置,1是产品编号不是数目,每个缓冲区数组单元代表一个产品,存的是产品编号(在1-10内)。

 

remain_total:表示缓冲区现在的产品数量。

 

Buffer_state:打印buffer10个数,里面存的是产品编号(1-10),0代表没有产品。

 

为了便于观察,我在void produce()void consume()函数里加了一句Sleep(1000),如果要加快程序可以把1000改小。

 

 

我用的是英文注释,p_count表示生产者进程数目,我设置为s_count为消费者进程,我设置为6,可改变他们的值从而改变不同进程的数目。

 

enter键可以终止程序,会出现一段信息:

 

总共生产了36个,消耗了30个。

 

 

/*
 * main.cpp
 *
 *  Created on: 2013-4-15
 *      Author: 许亚文

 */

#include<windows.h>
#include<iostream>

const unsigned short SIZE_OF_BUFFER=10; //the length of buffer
unsigned short buffer[SIZE_OF_BUFFER]={0}; //create space for buffer
unsigned short in=0;                   //the mark of position entering the space
unsigned short out=0;                  //the mark of position leaving the space
unsigned short Product_ID=0;           //the ID of product,from 1 to 10,not for count
unsigned short Consume_ID=0;           //the ID of consume product_ID in the buffer
unsigned int produce_sum=0;            //the total produce number
unsigned int consume_sum=0;            //the total consume number
HANDLE mutex;                          //the mutex between threads
HANDLE Full_Semaphore;                 //the resource semaphore: buffer is full
HANDLE Empty_Semaphore;                //the resource semaphore: buffer is empty
const unsigned short p_count=20;        //the number of produce one time
const unsigned short c_count=6;        //the number of consumer one time
const unsigned short s_count=p_count+c_count;  //the sum number of threads
HANDLE threads[s_count];               //the handle of every thread
DWORD Producer_ID[p_count];            //the mark of producer thread
DWORD Consumer_ID[c_count];            //the mark of consumer thread
unsigned short control=1;              //control the program run or stop


DWORD WINAPI producer(LPVOID);         //the producer thread
DWORD WINAPI consumer(LPVOID);         //the consumer thread
void produce();                                           
void consume();
void Create_P_Threads();               //create producer thread
void Create_C_Threads();               //create consumer thread
void Product_Sum();                    //print the total of remain product number and print the buffer
void info();                           //info


void Product_Sum()
{
 int i,sum=0;
 for(i=0;i<SIZE_OF_BUFFER;i++)
 {
  if(buffer[i]!=0)
   sum++;
 }
 std::cout<<"  "<<sum<<"         ";
 for(i=0;i<SIZE_OF_BUFFER;i++)
 {
  std::cout<<buffer[i]<<" ";
 }
 printf("\n");
}


void produce()
{
 int i;
 std::cout<<"produce";
 if(Product_ID>=10)
  Product_ID=0;
 Product_ID++;
 produce_sum++;
 buffer[in]=Product_ID;
 printf(" buffer[%d]=%d    ",in,Product_ID);
 in=(in+1)%SIZE_OF_BUFFER;
    Product_Sum();
}

void consume()
{
 int i;
 std::cout<<"consume";
 consume_sum++;
 Consume_ID=buffer[out];
 printf(" buffer[%d]=%d    ",out,Consume_ID);
 buffer[out]=0;
 out=(out+1)%SIZE_OF_BUFFER;
 Product_Sum();
}

DWORD WINAPI producer(LPVOID)                               //producer thread
{
 while(control)
 {
  WaitForSingleObject(Full_Semaphore,INFINITE);       //resource semaphore P operation
        WaitForSingleObject(mutex,INFINITE);                //the mutex P operation
  produce();
  Sleep(1000);
  ReleaseMutex(mutex);                                //resource semaphore P operation
  ReleaseSemaphore(Empty_Semaphore,1,NULL);            //the mutex P operation
 }
 return 0;
}

DWORD WINAPI consumer(LPVOID)                              //consumer thread
{
 while(control)
 {
  WaitForSingleObject(Empty_Semaphore,INFINITE);
  WaitForSingleObject(mutex,INFINITE);
  consume();
  Sleep(1000);
  ReleaseMutex(mutex);
  ReleaseSemaphore(Full_Semaphore,1,NULL);
 }
 return 0;
}

void Create_P_Threads()                                  //create producer thread
{
 for(int i=0;i<p_count;i++)
 {
  threads[i]=CreateThread(NULL,0,producer,NULL,0,&Producer_ID[i]);
  if(threads[i]==NULL)
   control=0;
 }
}


void Create_C_Threads()
{
 for(int i=p_count;i<s_count;i++)
 {
  threads[i]=CreateThread(NULL,0,consumer,NULL,0,&Consumer_ID[i-p_count]);
  if(threads[i]==NULL)
   control=0;
 }
}

 

void info()
{
 std::cout<<"\n"<<std::endl;
 std::cout<<"**********I did refer to the program on the web."<<std::endl;
    std::cout<<"*******and I simplify some things and make it more powful!"<<std::endl;
    std::cout<<"**But it is really a word a word knocked out by me based on understanding\n"<<std::endl;
 std::cout<<"produce/consume    remain_total  buffer_state(from 0 to 9)"<<std::endl;
}


int main()
{
 info();
 mutex=CreateMutex(NULL,FALSE,NULL);
 Full_Semaphore=CreateSemaphore(NULL,SIZE_OF_BUFFER,SIZE_OF_BUFFER,NULL);
 Empty_Semaphore=CreateSemaphore(NULL,0,SIZE_OF_BUFFER,NULL);
 Create_P_Threads();
 Create_C_Threads();
 while(control)
 {
  if(getchar())
  {
   std::cout<<std::endl;
   std::cout<<"the total produce product number is "<<produce_sum<<std::endl;
   std::cout<<"the total consume product number is "<<consume_sum<<std::endl;
   control=0;
  }
 }
 return 0;
}

 

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中实现线程的生产者消费者模型可以使用线程库pthread。下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define BUFFER_SIZE 5 int buffer[BUFFER_SIZE]; int count = 0; // 缓冲区中的数据数量 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁 pthread_cond_t empty = PTHREAD_COND_INITIALIZER; // 缓冲区为空的条件变量 pthread_cond_t full = PTHREAD_COND_INITIALIZER; // 缓冲区为满的条件变量 void* producer(void* arg) { int item; while (1) { item = rand() % 100; // 生成随机数作为生产的物品 pthread_mutex_lock(&mutex); // 加锁 while (count == BUFFER_SIZE) { // 如果缓冲区已满,等待 pthread_cond_wait(&empty, &mutex); } buffer[count++] = item; // 将物品放入缓冲区 printf("Producer produced item: %d\n", item); pthread_cond_signal(&full); // 唤醒等待的消费者 pthread_mutex_unlock(&mutex); // 解锁 } return NULL; } void* consumer(void* arg) { int item; while (1) { pthread_mutex_lock(&mutex); // 加锁 while (count == 0) { // 如果缓冲区为空,等待 pthread_cond_wait(&full, &mutex); } item = buffer[--count]; // 从缓冲区取出物品 printf("Consumer consumed item: %d\n", item); pthread_cond_signal(&empty); // 唤醒等待的生产者 pthread_mutex_unlock(&mutex); // 解锁 } return NULL; } int main() { pthread_t producer_thread, consumer_thread; pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); return 0; } ``` 这个示例代码中,定义了一个大小为5的缓冲区(使用数组实现),其中`count`变量表示缓冲区中的数据数量。生产者线程通过生成随机数作为物品,并将物品放入缓冲区。消费者线程从缓冲区中取出物品并进行消费。互斥锁`mutex`用于保护临界区资源的访问,条件变量`empty`和`full`用于实现生产者消费者之间的同步。 请注意,这只是一个简单的示例代码,没有考虑线程安全性和错误处理。在实际使用中,还需要更加细致的设计和处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值