我正在尝试使用互斥体来同步不同线程中多个方法的执行。 我创建了一个类 Bar,其中包含 foo 方法和互斥属性。 然后我想在线程中运行该 foo 方法。 我不明白为什么这是一个问题并且以下代码无法编译?以及如何解决这个问题?任何帮助表示赞赏。
#include <thread>
#include <mutex>
class Bar
{
public:
Bar (){};
void foo(){};
std::mutex m_;
};
int main(void)
{
Bar b;
std::thread t(&Bar::foo, b);
return 0;
}
我收到以下错误:
include/c++/7.3.0/thread:256:11: error: no matching constructor for initialization of '__decayed_tuple<void (Bar::*)(), Bar &>' (aka 'std::tuple<void (Bar::*)(), Bar>')
return { __decayed_tuple<_Callable, _Args...>{
和
include/c++/7.3.0/tuple:133:4: error: call to implicitly-deleted copy constructor of 'Bar'
: _M_head_impl(std::forward<_UHead>(__h)) { }
最佳答案
您应该将指针传递给 b,而不是 b 本身:
std::thread t(&Bar::foo, &b);
按照代码中的方式,您尝试按值传递,这涉及复制 - 并且互斥体没有复制构造函数,只有移动构造函数。
关于c++ - 使用包含互斥体的类的方法实例化 cpp11 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131278/