c++ - 如何在 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)...));
}
解决方案
我的回答有点晚了,但可能会有所帮助:
我找到了这样的解决方案:
您可以使用std::bind(function, arg1, arg2)
and std::ref
orstd::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 但想法类似于传递引用。
推荐阅读
- angular - 如何修复角度下拉列表中的重复数据
- c# - iOS 平台上的 Xamarin Forms 未收到 Appcenter 推送通知
- android - android布局中水平或垂直居中的含义
- cmake - CMake 创建了很多我没有指定的目标
- angular - 模式验证表达式,第一个字母大写的角度?
- java - 如何在 Java 中的另一个信号之上绘制峰值数组?
- python - 如何使用 value_counts() 返回的值做进一步的计算?
- php - phpmyadmin 显示代码而不是登录页面
- python - 回复收到的媒体消息 | Twilio Whatsapp API | 内部服务器错误
- excel - 在Excel VBA中将单个值分配给多个变量