【问题标题】:How to make 5 threads read and write array concurrently如何让5个线程同时读写数组
【发布时间】: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


【解决方案1】:

您的第一个问题是您将 条件变量 视为它们有记忆。在您的 main() 中,您是 pthread_cond_signal(),但此时,您不知道是否有任何线程正在等待该条件。由于条件变量没有记忆,你的信号很可能会丢失。

您的第二个问题是 o 受到条件的有效保护;因为每个消费者都使用它;并且每个生产者都修改它,你不能允许多个生产者或消费者同时执行。

您想要的解决方案相当于您从生产者那里注入 o 的队列;并在消费者中收集它们。这样一来,您的并发性就会受到您产生 o 的能力的限制。

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多