【问题标题】:std::bind a thread memeber variable to an instance of a classstd::将线程成员变量绑定到类的实例
【发布时间】:2020-04-22 05:43:42
【问题描述】:

我对创建成员线程以在类实例的成员函数上运行的各种方式以及它们之间的区别感到困惑:- 第一种方法——使用 lambda 表达式

auto m_thread = std::thread([this]{run();});

第二种方法

auto m_thread = std::thread(std::bind(&MyType::run, this));

第三种方法

auto res = std::bind(&m_thread, std::bind(&MyType::run, this));

第四种方法——

auto res = std::bind(&m_thread, &MyType::run, this);

在这里, m_thread 是std::thread m_thread 给出的Class MyType 的成员变量,其中this 是一个实例,run 是同一类的成员函数。所有这些都会给出相同的结果吗?它们是否等效?另外,在最后两种情况下如何让线程开始执行。

【问题讨论】:

  • std::bind 的第一个参数应该是可调用的(和可复制的)(但实际上不是用 SFINAE 完成的),std::thread 两者都不是。
  • 还有,简单地说,auto m_thread = std::thread(&MyType::run, this);
  • 那么确实,它们是将可调用对象转换为另一个可调用对象(并可能绑定某些参数)的几种方法。
  • @Jarod42 所以,本质上,最后两种方法是行不通的。前两种方法是等价的。我说的对吗?
  • 总之,是的..

标签: c++ c++11 stdbind


【解决方案1】:

std::bind 期望第一个参数是可调用的(但不拒绝无效参数)。

所以第 3 和第 4 方法创建了不可用的对象。

要创建std::thread,您确实有几个可用的变体:

  • std::thread(&MyType::run, this);
  • std::thread(std::bind(&MyType::run, this)); 上面没有优势。
  • std::thread([this](){ return this->run(); ); 允许处理 run 重载,默认参数。

【讨论】:

  • 前两个选项怎么没用std::men_fn()
  • @einpoklum 你能详细说明一下吗?
  • @abhiverma mem_fn 在普通的成员函数指针上一无所获; std::thread 可以隐式处理。
猜你喜欢
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多