gpt4 book ai didi

c++ - 生产者/消费者设计 - 在 Qt 中跨线程共享队列变量

转载 作者:行者123 更新时间:2023-11-30 04:33:36 25 4
gpt4 key购买 nike

我尝试以生产者-消费者模式创建并发队列类。

我的类(class)基于 http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

在我的主线程中,我使用 Qt::Concurrent 调用了以下两个方法

QFutureWatcher<void> *loadwatcher;
loadwatcher = new QFutureWatcher<void>();
QString filename("myfile");
QFuture<void> future = QtConcurrent::run(this, &EraserBatch::loadTiles,filename);
loadwatcher->setFuture(future);


QFutureWatcher<bool> *procwatcher;
procwatcher = new QFutureWatcher<bool>();
QFuture<bool> procfuture = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher->setFuture(procfuture);

所以 loadTiles 是我的生产者,processTile 是我的消费者。

在 loadtiles 中,我有一个像这样加载图 block 的循环:

for(int i =0; i < nXBlocks; i++)
{
for(int j = 0; j < nYBlocks; j++)
{
Tile *ipi = new Tile(filename);
sleep(1);
qDebug()<<"Tile pushed to queue:"<<i<<" "<<j << " Thread id:"<<this->thread();
this->tiles->push(ipi);
}
}

在消费者方法中,我有以下内容:

Tile *tile;
this->tiles->wait_and_pop(tile);

while(!tiles->empty())
{
qDebug()<<"Tile popped from queue:"<<tile->tilePosX<<" "<<tile->tilePosY<< " Thread id: " << this->thread();
sleep(5);
tiles->wait_and_pop(tile);
}

这似乎将所有图 block 都推送到队列中,但似乎我的消费者从未进入 while 循环,因为我弹出了第一个图 block ,然后队列为空。

所以这是一个设计缺陷 - 但我想我需要知道如何告诉生产者等待所有的图 block 被添加到队列中,并一直等到所有图 block 都完成。我需要弹出 while 循环外的第一个图 block ,以获取将在循环中使用的变量的一些设置信息,并分配一些我不想一遍又一遍地做的内存和 suhc。设置它的最佳方法是什么?

最佳答案

在这种情况下,生产者需要告诉消费者不会再有数据了。通常这是通过在队列上使用类似 Close() 方法的方法来实现的。您的消费者测试将变成:

while (!tiles->empty() || !tiles->closed())
{
... blocking consume
}

关于c++ - 生产者/消费者设计 - 在 Qt 中跨线程共享队列变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6700960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com