首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何让5个线程并发读写数组

如何让5个线程并发读写数组
EN

Stack Overflow用户
提问于 2021-09-07 18:06:29
回答 1查看 89关注 0票数 0

我正在尝试解决c++中著名的生产者-消费者问题,我想出了一个类似这样的实现……

代码语言:javascript
运行
复制
#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在数组中添加元素:元素为6

6,0,0,0,0,0,0

EN

回答 1

Stack Overflow用户

发布于 2021-09-08 23:22:18

您的第一个问题是,您将条件变量视为具有内存。在main()中,您可以使用pthread_cond_signal(),但是在这一点上,您不知道是否有线程在等待该条件。因为条件变量没有内存,你的信号很可能会丢失。

你的第二个问题是o受到条件的有效保护;因为每个消费者都在使用它;每个生产者都会修改它,所以你既不允许多个生产者也不允许消费者同时执行。

您想要的解决方案相当于一个队列,您将o从生产者注入其中;并将其收集到消费者中。这样,你的并发性就被你产生o的能力所限制了。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69092764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档