【发布时间】:2026-01-29 13:40:01
【问题描述】:
所以我有一个对象,它有一个我想要线程化的成员函数。由于这个函数将在对象之外操作一些资源,我想通过引用传递一个互斥锁作为这个函数的参数:
#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...>)
^
我怀疑它与 std::mutex 的不可复制性有关,也许 g++ 中的 std::ref 实现与 vc++ 中的不同?不过,这只是一个随机猜测。
有没有人精通这两种不同 C++ 编译器的精妙之处,知道是什么导致了这个问题,以及如何解决这个问题?
【问题讨论】:
-
@RichardHodges g++ 4.8.4
标签: c++ multithreading c++11 g++ mutex