分配给 运行 QFuture

Assigning to running QFuture

我可以将另一个 QFuture 对象分配给已经 运行 QFuture 对象吗?就像下面的例子:

 QFuture<int> future = QtConcurrent::run(function);
 future = QtConcurrent::run(anotherFunciton); //assume that future is still running at this point

我意识到这个特定的例子没有多大意义,它只是为了举例。假设第一个函数的结果不再让我感兴趣,进行这样的分配是否安全?还是我必须先取消它?如果是这样,我是否必须等待取消完成?

 QFuture<int> future = QtConcurrent::run(function);
 future.cancel();
 future.waitForFinished(); //is waiting necessary?
 future = QtConcurrent::run(anotherFunciton);

来自http://doc.qt.io/qt-4.8/qtconcurrentrun.html

Note that the QFuture returned by QtConcurrent::run() does not support canceling, pausing, or progress reporting. The QFuture returned can only be used to query for the running/finished status and the return value of the function.

意思是即使你想,你也不能取消你的QFuture。还有,就算可以取消,为什么要取消然后等着完成呢?

来自http://doc.qt.io/qt-4.8/qthreadpool.html#expiryTimeout-prop

Threads that are unused for a certain amount of time will expire. The default expiry timeout is 30000 milliseconds (30 seconds). This can be changed using setExpiryTimeout(). Setting a negative expiry timeout disables the expiry mechanism.

由于 QtConcurrent::run() 启动的线程由 QThreadPool class 管理,因此假设您没有指定负到期超时,您应该能够 future = QtConcurrent::run(anotherFunciton); 没有问题;原始线程将过期并退出。然而,这样做的效率值得怀疑。