所以我有一個具有我想要線程的成員函數的對象。由於這個功能將被操縱的一些資源的對象外,我要通過引用傳遞互斥作爲參數傳遞給該函數:將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 –