Mat*_*zak 3 multithreading c++11
我的代码剪断如下:
#include <iostream>
#include <thread>
class Me{
public:
bool isLearning;
void operator()(bool startLearning){
isLearning = startLearning;
}
};
int main(){
Me m;
std::thread t1(m(true));
t1.join();
std::cout << m.isLearning << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
传递参数时,我无法使用可调用对象启动线程,有没有办法在线程构造函数中启动线程并使用参数传递可调用对象?
问题#1
std::thread t1(m(true)); 不会做你认为它做的事情.
在这种情况下,您正在调用函数对象并将其结果(无效)传递给std :: thread的构造函数.
解
尝试传递您的函数对象和参数,如下所示:
std::thread(m, true);
问题#2
std::thread将获取您的函数对象的副本,以便它使用和修改的那个不会与声明的相同main.
解
尝试通过m使用传递引用std::ref.
std::thread(std::ref(m), true);
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |