简体   繁体   English

Qt线程设计生产者消费者

[英]Qt thread design producer consumer

The main thread is loading tasks into a queue. 主线程将任务加载到队列中。 A worker thread is dealing with these tasks. 一个工作线程正在处理这些任务。

My code is like this: 我的代码是这样的:

//Core subclass a QThread
Core::AddTask()
{ ...
  mutex.lock();
  tasks.append(task);
  mutex.unlock();
  start();//which calls the run function
}

Core::RefreshTask()
{ ...
  mutex.lock();
  tasks.clear();
  mutex.unlock();
  // Calculate the new tasks...
  ...
  //foreach newly added task call
  AddTask();
}

Core::run()
{ ...
  while (1)
{
  finish = false;
  mutex.lock();
  tasks.dequeue();
  if (tasks.size() == 0)
    finish = true;
  mutex.unlock();
  ...
  if (finish)
     break;
}
}

However I found the worker thread failed to finish all the tasks because when the run function is being processed, it will not response to start() call. 但是,我发现工作线程无法完成所有任务,因为在处理运行功能时,它不会响应start()调用。 Then in the situation that: the run function is processing the last task and in the sametime AddTask is being called, then its start() call will do nothing. 然后,在以下情况下:run函数正在处理最后一个任务,并且在调用AddTask的同时,则其start()调用将无效。 And the run() function finish and ignore the task. 然后run()函数完成并忽略该任务。

I know a signal/slot mechanism could solve the problem. 我知道信号/插槽机制可以解决此问题。 But I am forced to use the old QThread::run() style multithreading... Any suggestions how to properly write a producer consumer pattern in Qt? 但是我被迫使用旧的QThread :: run()样式多线程...任何建议如何在Qt中正确编写生产者使用者模式?

I think you don't need call start() in Core::AddTask() . 我认为您不需要在Core::AddTask()调用start() Core::AddTask() When you add new task to task list, you can send some kind of event message. 将新任务添加到任务列表时,可以发送某种事件消息。 It can be Qt signal, condition variable or something else. 它可以是Qt信号,条件变量或其他。

Event loop works in separate thread and process tasks. 事件循环在单独的线程和流程任务中工作。 If task list is empty, event loop waits for an event. 如果任务列表为空,则事件循环等待事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM