为啥我不能将带有互斥锁的仿函数传递给线程?

Posted

技术标签:

【中文标题】为啥我不能将带有互斥锁的仿函数传递给线程?【英文标题】:Why can't I pass in a functor with a mutex to a thread?为什么我不能将带有互斥锁的仿函数传递给线程? 【发布时间】:2020-08-16 05:31:10 【问题描述】:
class test

    std::mutex m1;

public:
    inline static int i0;
    void operator()()
    
        m1.lock();
        ++i;
        m1.unlock();
    
;


int main()

    test t;
    std::thread t1t; // doesn't work
    // std::thread t1std::ref(t); // works

    t1.join();

    cout << test::i << endl;

错误:

In file included from test.cpp:19:
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:365:17: error: no matching constructor for initialization of
      '_Gp' (aka 'tuple<unique_ptr<std::__1::__thread_struct>, test>')
            new _Gp(std::move(__tsp),
                ^   ~~~~~~~~~~~~~~~~~
test.cpp:53:17: note: in instantiation of function template specialization 'std::__1::thread::thread<test &, void>' requested
      here
    std::thread t1t; // doesn't work
                ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:625:5: note: candidate template ignored: requirement
      '__lazy_and<is_same<allocator_arg_t, unique_ptr<__thread_struct, default_delete<__thread_struct> > >,
      __lazy_all<__dependent_type<is_default_constructible<unique_ptr<__thread_struct, default_delete<__thread_struct> > >,
      true>, __dependent_type<is_default_constructible<test>, true> > >::value' was not satisfied [with _AllocArgT =
      std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, _Alloc = test,
      _Dummy = true]
    tuple(_AllocArgT, _Alloc const& __a)
    ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:641:5: note: candidate template ignored: requirement
      '_CheckArgsConstructor<true>::template __enable_implicit<const std::__1::unique_ptr<std::__1::__thread_struct,
      std::__1::default_delete<std::__1::__thread_struct> > &, const test &>()' was not satisfied [with _Dummy = true]
    tuple(const _Tp& ... __t) _NOEXCEPT_((__all<is_nothrow_copy_constructible<_Tp>::value...>::value))
    ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:659:14: note: candidate template ignored: requirement
      '_CheckArgsConstructor<true>::template __enable_explicit<const std::__1::unique_ptr<std::__1::__thread_struct,
      std::__1::default_delete<std::__1::__thread_struct> > &, const test &>()' was not satisfied [with _Dummy = true]
    explicit tuple(const _Tp& ... __t) _NOEXCEPT_((__all<is_nothrow_copy_constructible<_Tp>::value...>::value))
             ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:723:9: note: candidate template ignored: requirement
      '_CheckArgsConstructor<sizeof...(_Up) == sizeof...(_Tp) && !false>::template
      __enable_implicit<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >,
      test>() || _CheckArgsConstructor<_EnableImplicitReducedArityExtension && sizeof...(_Up) < sizeof...(_Tp) &&
      !false>::template __enable_implicit<std::__1::unique_ptr<std::__1::__thread_struct,
      std::__1::default_delete<std::__1::__thread_struct> >, test>()' was not satisfied [with _Up =
      <std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, test>,
      _PackIsTuple = false]
        tuple(_Up&&... __u)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:756:9: note: candidate template ignored: requirement
      '_CheckArgsConstructor<sizeof...(_Up) <= sizeof...(_Tp) && !_PackExpandsToThisTuple<unique_ptr<__thread_struct,
      default_delete<__thread_struct> >, test>::value>::template
      __enable_explicit<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >,
      test>() || _CheckArgsConstructor<!_EnableImplicitReducedArityExtension && sizeof...(_Up) < sizeof...(_Tp) &&
      !_PackExpandsToThisTuple<unique_ptr<__thread_struct, default_delete<__thread_struct> >, test>::value>::template
      __enable_implicit<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >,
      test>()' was not satisfied [with _Up = <std::__1::unique_ptr<std::__1::__thread_struct,
      std::__1::default_delete<std::__1::__thread_struct> >, test>]
        tuple(_Up&&... __u)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:783:9: note: candidate template ignored: requirement
      '_CheckArgsConstructor<sizeof...(_Up) == sizeof...(_Tp) && !_PackExpandsToThisTuple<>::value>::template
      __enable_implicit<>()' was not satisfied [with _Alloc = test, _Up = <>]
        tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:803:9: note: candidate template ignored: requirement
      '_CheckArgsConstructor<sizeof...(_Up) == sizeof...(_Tp) && !_PackExpandsToThisTuple<>::value>::template
      __enable_explicit<>()' was not satisfied [with _Alloc = test, _Up = <>]
        tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:612:23: note: candidate constructor template not viable: requires
      0 arguments, but 2 were provided
    _LIBCPP_CONSTEXPR tuple()
                      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:677:7: note: candidate constructor template not viable: requires 4
      arguments, but 2 were provided
      tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:697:7: note: candidate constructor template not viable: requires 4
      arguments, but 2 were provided
      tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:822:9: note: candidate constructor template not viable: requires
      single argument '__t', but 2 arguments were provided
        tuple(_Tuple&& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, _Tuple>::value))
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:837:9: note: candidate constructor template not viable: requires
      single argument '__t', but 2 arguments were provided
        tuple(_Tuple&& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, _Tuple>::value))
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:850:9: note: candidate constructor template not viable: requires 3
      arguments, but 2 were provided
        tuple(allocator_arg_t, const _Alloc& __a, _Tuple&& __t)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:864:9: note: candidate constructor template not viable: requires 3
      arguments, but 2 were provided
        tuple(allocator_arg_t, const _Alloc& __a, _Tuple&& __t)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:615:5: note: candidate constructor not viable: requires 1
      argument, but 2 were provided
    tuple(tuple const&) = default;
    ^
In file included from test.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/iostream:38:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/ios:216:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__locale:15:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/string:500:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/string_view:176:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__string:56:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:640:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/initializer_list:47:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/cstddef:110:
/Library/Developer/CommandLineTools/usr/include/c++/v1/type_traits:2360:12: error: call to implicitly-deleted copy constructor
      of 'typename decay<test &>::type' (aka 'test')
    return _VSTD::forward<_Tp>(__t);
           ^~~~~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/__config:508:15: note: expanded from macro '_VSTD'
#define _VSTD std::_LIBCPP_NAMESPACE
              ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:366:21: note: in instantiation of function template
      specialization 'std::__1::__decay_copy<test &>' requested here
                    __decay_copy(_VSTD::forward<_Fp>(__f)),
                    ^
test.cpp:53:17: note: in instantiation of function template specialization 'std::__1::thread::thread<test &, void>' requested
      here
    std::thread t1t; // doesn't work
                ^
test.cpp:36:16: note: copy constructor of 'test' is implicitly deleted because field 'm1' has an inaccessible copy constructor
    std::mutex m1;
               ^
2 errors generated.

当我将仿函数传入线程时,该程序无法编译。但是当我用std::ref 包装它时它会起作用。看来类成员互斥锁是问题所在,但我不知道为什么。有人能解释一下为什么 std::ref 包装器允许它编译但没有它,程序就无法编译?

编译器错误消息似乎没有帮助。

【问题讨论】:

想想一个可复制的想法mutexs 会有多糟糕。 @john 哦,我明白了(我处于(错误的)假设之下,即线程的行为与 C++ 规范不同)。所以在这种情况下,当函子被传入时,它会被复制,这意味着互斥体被复制了。为什么这是一个问题? 线程的默认行为是进行复制。除其他外,这可以避免在线程完成之前必须跨线程同步数据以及数据超出范围的一般麻烦。 A mutex 将多个线程排除在代码的同一关键部分之外。如果不同线程拥有mutex的不同副本,它们都可以锁定自己的副本,进入临界区,使mutex无用。 @Someprogrammerdude 与使用std::ref(t) 的效果不一样吗? 【参考方案1】:

threads 的默认行为是进行复制。除其他外,这可以避免在线程完成之前必须跨线程同步数据以及数据超出范围的一般麻烦。

在这种特定情况下,被复制的对象包含mutex,而mutexs 不能被复制或移动。 mutex 将多个线程排除在代码的同一关键部分之外。如果不同线程拥有mutex的不同副本,它们都可以锁定自己的副本并进入临界区,从而使mutex无用。它们必须共享同一个mutex,在这种情况下,这意味着所有线程都必须共享同一个test

在这种情况下,static mutex m1 除了通过引用传递之外,将是一个可行的解决方案。

注意:因为ipublic 并且任何人都可以访问,所以任何人都可以轻松访问i,无论mutex 是什么。

注意:最好使用std::lock_guardstd::scoped_lock,而不是手动调用lock 和unlock。 lock_guardscoped_lock 在构造时锁定 mutex 并在销毁时解锁,保证当锁定对象超出范围时 mutex 将被解锁。

注意:删除 mutex 并使用 std::atomic&lt;int&gt; 代替 int 应该可以解决大多数同步问题。

【讨论】:

如果您要在一个类中拥有一个互斥锁,将其设为静态通常是最佳做法吗? 这需要根据具体情况来决定。这是一个很好的解决方案,因为它保护的变量是static

以上是关于为啥我不能将带有互斥锁的仿函数传递给线程?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我不能将函数指针作为模板参数传递给地图?

为啥threading.thread将空字典传递给python中的函数线程

为啥函数的 dtors 被调用两次(多次),当作为函数的参数传递给线程时?

AfxBeginThread 破坏了作为参数传递给线程函数的类中的 LPWSTR 值。为啥?

实现一个可以存储其函数参数的仿函数模板

为啥 lambda auto& 参数选择 const 重载?