使用std :: mutex作为参数线程化成员函数

时间:2016-04-07 09:39:23

标签: c++ multithreading c++11 g++ 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...>)
        ^

我怀疑它与std :: mutex的不可复制性有关,也许g ++中的std :: ref实现与vc ++中的不同?这只是一个随机的猜测。

是否有精通两个不同C ++编译器细微之处的人知道是什么导致了这个问题,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

当传递指向对象的指针而不是引用(包装器)时,这将以g ++编译:

std::thread bar_thread( &foo::bar, &a, std::ref( m ) );

显然,正如理查德·霍奇斯(Richard Hodges)所回答的那样,直到C ++ 17才支持引用包装器作为被调用者。