【发布时间】:2021-11-04 14:51:44
【问题描述】:
我正在尝试解决 C++ 中著名的生产者-消费者问题,我想出了一个这样的实现......
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
void *consumeThread(void *i);
void *produceThread(void *i);
using std::cout;
using std::endl;
//Bucket size
#define Bucket_size 10
int buckets[Bucket_size];
pthread_mutex_t lock;
pthread_cond_t consume_now, produce_now;
time_t timer;
int o = 0;
int p = 0;
int main()
{
int i[5] = {1, 2, 3, 4, 5};
pthread_t consumer[5];
pthread_t producer[5];
pthread_mutex_init(&lock, nullptr);
pthread_cond_init(&consume_now, nullptr);
pthread_cond_init(&produce_now, nullptr);
timer = time(nullptr) + 10;
srand(time(nullptr));
for (int x = 0; x < 5; x++)
{
pthread_create(&producer[x], nullptr, &produceThread, &i[x]);
}
for (int x = 0; x < 5; x++)
{
pthread_create(&consumer[x], nullptr, &consumeThread, &i[x]);
}
pthread_cond_signal(&produce_now);
for (int x = 0; x < 5; x++)
{
pthread_join(producer[x], nullptr);
pthread_join(consumer[x], nullptr);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&consume_now);
pthread_cond_destroy(&produce_now);
return 0;
}
void *consumeThread(void *i)
{
bool quit = false;
while (!quit)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&consume_now, &lock);
printf("thread %d consuming element at array[%d] : the element is %d \n", *((int *)i), o, buckets[o]);
buckets[o] = 0;
p++;
printArray();
usleep(100000);
pthread_cond_signal(&produce_now);
pthread_mutex_unlock(&lock);
quit = time(nullptr) > timer;
}
return EXIT_SUCCESS;
}
void *produceThread(void *i)
{
int a = 0;
bool quit = false;
while (!quit)
{
o = p % 10;
buckets[o] = (rand() % 20) + 1;
printf("thread %d adding element in array[%d] : the element is %d \n", *((int *)i), o, buckets[o]);
a++;
printArray();
usleep(100000);
quit = time(nullptr) > timer;
}
return EXIT_SUCCESS;
}
目前这个解决方案有5个生产者线程和5个消费者线程,但是它一次只允许1个线程生产和1个线程消费,有没有办法让5个生产者和消费者线程同时工作?
程序的示例输出:
线程 1 在数组 [0] 中添加元素:元素为 6
[6,0,0,0,0,0,0,0,0,0]
【问题讨论】:
-
这很像 C,生产者-消费者设计只需要线程安全队列和可选阻塞
T pop()。首先创建一个Queue类,然后工作线程变得非常容易并且不知道多线程。将多线程代码集中到尽可能少的地方通常是最好的。 -
为什么不使用 C++ 线程?
标签: c++ c multithreading pthreads