QtCurrent与成员函数和线程池兼容

QtConcurrent with member function and thread pool

本文关键字:线程 成员 函数 QtCurrent      更新时间:2023-10-16

我可以使用QtConcurrent::run在单独的线程中运行成员函数。我使用以下代码:

QFuture<MyObject> future = QtConcurrent::run(this, &MyClass::doSomething, param1, param2);

现在我想使用一个自定义的QThreadPool,而不是全局的,因为这个任务的线程数量应该是可配置的。根据文档,我尝试了以下代码,但不幸的是,它找不到合适的重载。

QThreadPool pool;
QFuture<MyObject> future = QtConcurrent::run(&pool, this, &MyClass::doSomething, param1, param2);

是否支持此功能?

AFAIK、QThreadPoolQtConcurrent不能混合在一起

如果要使用QThreadPool,则需要定义QRunnable的实例,该实例可以在其run()函数中调用函数MyClass::doSomething

/* code not tested */
class RunnableHelper: public QObject, public QRunnable
{
    Q_OBJECT
    /* param1, param2 storage */
public:
    explicit RunnableHelper(param1, param2);
    void run()
    {
        MyClass::doSomething(param1, param2);
    }
};
RunnableHelper* rh= new RunnableHelper(param1, param2);
QThreadPool::globalInstance()->start(rh);

聚会迟到了一点;还

这是可能的。我所做的是

QThreadPool *pool;
pool = new QThreadPool() ;
.
.
QFuture<MyObject> future = QtConcurrent::run(pool, ...);