所以我有一个具有我想要线程的成员函数的对象。由于这个功能将被操纵的一些资源的对象外,我要通过引用传递互斥作为参数传递给该函数:将std :: mutex作为参数的成员函数的线程化
#include <iostream>
#include <mutex>
#include <thread>
class foo
{
public:
void bar(std::mutex &m)
{
std::lock_guard<std::mutex> lock(m);
std::cout << "Threading this function works!" << std::endl;
}
};
int main()
{
foo a;
std::mutex m;
std::thread bar_thread(&foo::bar, std::ref(a), std::ref(m));
bar_thread.join();
return 0;
}
此编译和运行在Visual Studio 2013/VC++细。但是,当我尝试在g ++中编译时失败。该错误消息也很神秘,这使得它很难理解什么编译器抱怨:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (foo::*)(std::mutex&)>(std::reference_wrapper<foo>, std::reference_wrapper<std::mutex>)>’:
/usr/include/c++/4.8/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (foo::*)(std::mutex&); _Args = {std::reference_wrapper<foo>, std::reference_wrapper<std::mutex>}]’
thread_test.cpp:63:69: required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (foo::*)(std::mutex&)>(std::reference_wrapper<foo>, std::reference_wrapper<std::mutex>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (foo::*)(std::mutex&)>(std::reference_wrapper<foo>, std::reference_wrapper<std::mutex>)>’
_M_invoke(_Index_tuple<_Indices...>)
^
我有这事做性病的非复制性::互斥体,也许是怀疑g ++中的std :: ref实现与vC++中的不同?这只是一个随机猜测。
任何熟悉两种不同C++编译器精妙之处的人都知道是什么导致了这个问题,以及它如何解决?
版本的gcc? –
@RichardHodges g ++ 4.8.4 –