gpt4 book ai didi

multithreading - 如何使用带参数的函数对象启动线程

转载 作者:行者123 更新时间:2023-12-01 08:52:48 24 4
gpt4 key购买 nike

我在下面截取了代码:

#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;
}

当参数传递时我不能用可调用对象启动线程,有没有办法在线程构造函数中启动线程并用参数传递可调用对象?

最佳答案

问题 #1

std::thread t1(m(true)); 不会做你认为的那样。

在这种情况下,您正在调用您的函数对象并将其结果(无效)传递给 std::thread 的构造函数。 .

解决方案

尝试像这样传递你的函数对象和参数:

std::thread(m, true);

问题 #2

std::thread 将获取您的函数对象的副本,因此它使用和修改的对象将与 main 中声明的对象不同。

解决方案

尝试使用 std::ref 传递对 m 的引用。

std::thread(std::ref(m), true);

关于multithreading - 如何使用带参数的函数对象启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37676157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com