首页 > 解决方案 > 如何在 QThread 中传递引用

问题描述

我如何从 QThread 传递引用,我尝试通过与 std::thread 相同的方法来执行此操作,但没有成功。

使用 std::thread 的示例代码

void test(int value, int &value2)
{
    value2 = value1 + 1;
    return;
}

int main()
{
   int value1 = 100;
   int value2 = NULL;

   std::thread thread(Testex, value1, std::ref(value2));
   thread.detach();

   std::cout << value2;
}

我尝试使用的代码,但在编译时出现以下错误:“没有匹配函数调用'invoke(std::remove_reference::type, int, int*)'”

void test(int value, int &value2)
{
    value2 = value1 + 1;
    return;
}

int main()
{
    int value1 = 100;
    int value2 = NULL;

    QThread* qthread = QThread::create(test, value1, &value2);
    qthread ->start();

    qDebug() << value2;

    return 0;
}

包含错误的 qthread.h 的一部分:

template <typename Function, typename... Args>
QThread *QThread::create(Function &&f, Args &&... args)
{
    using DecayedFunction = typename std::decay<Function>::type;
    auto threadFunction =
        [f = static_cast<DecayedFunction>(std::forward<Function>(f))](auto &&... largs) mutable -> void
        {
            (void)std::invoke(std::move(f), std::forward<decltype(largs)>(largs)...);
        };

    return createThreadImpl(std::async(std::launch::deferred,
                                       std::move(threadFunction),
                                       std::forward<Args>(args)...));
}

标签: c++qtreferenceqthread

解决方案


我的回答有点晚了,但可能会有所帮助:

我找到了这样的解决方案:

您可以使用std::bind(function, arg1, arg2)and std::reforstd::reference_wrapper<type>(var)来传递引用参数。

最终代码如下:

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>

void test(int value1, int &value2)
{
    value2 = value1 + 1;
    return;
}
int main(int argc, char *argv[])
{
    //QApplication a(argc, argv);
    //MainWindow w;
    //w.show();

    int value1 = 100;
    int value2 = 0;
    qDebug()<<"Value 1" << value1;
    QThread* qthread = QThread::create(std::bind(test,value1, std::ref(value2)));
    //This also works
    // QThread* qthread = QThread::create(std::bind(test,value1, std::reference_wrapper<int>(value2)));
    qthread ->start();
    // waiting for QThread to finish its task otherwise we would read the old value of value which is 0 instead of 101
    qthread->wait(); 
    // read only after the thread finishes
    qDebug()<<"Value 2" << value2;

    return 0;
}

不要忘记等待QThread完成,否则您将读取以前的值而不是由QThread

此代码将给出如下结果:

Value 1 100
Value 2 101

备注:我不得不使用语法QThread *QThread::create(Function &&f)QThread::create(Function &&f, Args &&... args)不像你),因为我没有 C++17 但想法类似于传递引用。


推荐阅读