使用包含互斥锁的 class 方法实例化 cpp11 线程

Instanciate a cpp11 thread with a method of a class that contains a mutex

我正在尝试使用互斥体来同步不同线程中多个方法的执行。 我创建了一个 class Bar,其中包含一个 foo 方法和一个 mutex 属性。 然后我想在线程中 运行 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);

在您的代码中,您正试图按值传递,这涉及复制 - 互斥体没有复制构造函数,只有移动构造函数。