【问题标题】:Is there a way to detect when a QT QRunnable object is done?有没有办法检测 QT QRunnable 对象何时完成?
【发布时间】:2010-10-14 07:26:08
【问题描述】:

有没有办法检测 QT QRunnable 对象何时完成? (除了在 r​​un() 方法结束时手动创建一些信号事件。)

【问题讨论】:

    标签: multithreading qt threadpool


    【解决方案1】:

    您可以简单地使用 QtConcurrent 来运行 runnable 并使用 QFuture 等待完成。

    #include <QtConcurrentRun>
    
    class MyRunnable : public Runnable{
      void run();
    }
    

    为了运行并等待它,您可以执行以下操作

    //create a new MyRunnable to use
    MyRunnable instance;
    
    //run the instance asynchronously
    QFuture<void> future = QtConcurrent::run(&instance, &MyRunnable::run);
    
    //wait for the instance completion
    future.waitForFinished();
    

    Qtconcurrent::run 将启动一个新线程以在实例上执行方法 run() 并立即返回一个跟踪实例进度的 QFuture。

    但请注意,使用此解决方案您有责任在执行期间将实例保存在内存中。

    【讨论】:

    • 我认为 QtConcurrent::run 实际上并没有使用 QRunnable ...在您的示例中,您从类 Runnable (QRunnable?) 派生 - 但我想它可以在不派生任何类的情况下工作?跨度>
    • 确实,我只是想让示例尽可能接近请求。你当然是对的:myRunnable 可能是任何类。
    【解决方案2】:

    可能有,或者你可能需要稍微更高一点。 QFutureQFutureWatcher 类旨在与 Qt 的 Concurrent frameworkQFutureWatcherhas a signal 一起工作,当它正在观看的项目完成时。

    【讨论】:

    • 你能详细说明一下吗?我应该如何将 QRunnable 与 QFuture 关联?还是您建议不要使用 QRunnable?
    【解决方案3】:

    您可以添加自己的 SIGNAL,它会作为您的 run() 方法所做的最后一件事发出。然后在调用connect(...);之前将其连接到对应的SLOT

    【讨论】:

    • 请注意,您需要从 QRunnable 和 QObject 继承您的类才能做到这一点。
    • 也可以直接使用 QMetaObject::invokeMethod() 调用槽。如果您使用 Qt::QueuedConnection,您可以在另一个线程的上下文中安全地调用槽。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多