为什么不能将带有互斥量的仿函数传递给线程?

如何解决为什么不能将带有互斥量的仿函数传递给线程?

class test
{
    std::mutex m1;

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


int main()
{
    test t;
    std::thread t1{t}; // doesn't work
    // std::thread t1{std::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 t1{t}; // 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,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,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,test>() || _CheckArgsConstructor<_EnableImplicitReducedArityExtension && sizeof...(_Up) < sizeof...(_Tp) &&
      !false>::template __enable_implicit<std::__1::unique_ptr<std::__1::__thread_struct,test>()' was not satisfied [with _Up =
      <std::__1::unique_ptr<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,test>() || _CheckArgsConstructor<!_EnableImplicitReducedArityExtension && sizeof...(_Up) < sizeof...(_Tp) &&
      !_PackExpandsToThisTuple<unique_ptr<__thread_struct,test>::value>::template
      __enable_implicit<std::__1::unique_ptr<std::__1::__thread_struct,test>()' was not satisfied [with _Up = <std::__1::unique_ptr<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&&... __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 _Tp& ... __t)
      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:697:7: note: candidate constructor template not viable: requires 4
      arguments,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',_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,_Tuple&& __t)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/tuple:864:9: note: candidate constructor template not viable: requires 3
      arguments,_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 t1{t}; // 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包装器允许对此进行编译,但是如果没有包装,程序将无法编译?

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

解决方法

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

在这种特定情况下,要复制的对象包含mutex,并且mutex s无法复制或移动。 mutex使多个线程脱离同一关键代码段。如果不同的线程具有mutex的不同副本,则它们都可以锁定其副本并进入关键部分,从而使mutex无效。它们必须都共享相同的mutex,在这种情况下,这意味着所有线程都必须共享相同的test

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

注意:由于ipublic且任何人都可以访问,因此无论i为何,任何人都可以轻松访问mutex

注意:首选使用std::lock_guardstd::scoped_lock而不是手动调用锁定和解锁。 lock_guardscoped_lock会在构造时锁定mutex,并在破坏时解锁,从而保证mutex在锁定对象超出范围时将被解锁。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-