c++ - QThreadPool 示例

标签 c++ multithreading qt threadpool

我正在寻找一些关于使用 QThreadPool 的简明示例。这是我的使用方法:

QThreadPool *thread_pool = QThreadPool::globalInstance();
MyThread *thread = new MyThread();
thread_pool->start(thread);


class MyThread : public QRunnable {
public:
    MyThread();
    ~MyThread();
    void run();
};

void MyThread::run()
{
    qDebug() << "MyThread";
}

以上是正确的做法吗?
PS:我在引用中看到了waitForDone,请问什么时候调用waitForDone

最佳答案

除了一个异常(exception),这几乎是正确的。 QRunnable 不是线程,您不应该调用您的类 MyThreadMyRunnableMyTask 更正确。

请注意,您的代码与 documentation page 上的示例几乎相同.文档是简明示例的最佳来源。

当您想等待所有可运行对象都被处理时,您应该调用 waitForDone。这取决于您应用的架构。通常是在您创建并启动所有 QRunnable 并希望使用它们的结果时。

关于c++ - QThreadPool 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17235873/

相关文章:

c++ - freopen和cout创建内部错误

c++ - 按钮应该消耗鼠标事件吗?

python - Odoo:在 Thread 中调用 self.env 或其他模型

python - 子类化 QGraphicsLayoutItem 以显示像素图

c++ - 依赖倒置原则对项目结构有哪些影响?

c# - 如何捕获线程执行中方法返回的值#

c++ - 将使用 CreateEvent 和 WaitForMultipleObjects 的程序移植到 Linux

c++ - QT6: "qt.qpa.plugin: Could not load the Qt platform plugin "xcb"in ""即使它被发现了。"

qt - Qt 默认情况下 qDebug qWarning qCritical 和 qFatal 日志位于何处?

c++ - 无法打开缺少的库