c++ - 使用或不使用 boost::bind() 创建一个 boost::thread

标签 c++ boost boost-thread

有些人似乎使用 boost::bind() 函数启动 boost::threads,例如在以下问题的公认答案中:

Using boost thread and a non-static class function

而其他人根本不使用它,例如在这个问题中获得最多赞成票的答案:

Best way to start a thread as a member of a C++ class?

那么,如果存在差异,那有什么区别呢?

最佳答案

从下面编译并给出预期输出的代码可以看出,boost::bind 对于将 boost::thread 与自由函数、成员函数和静态成员函数一起使用是完全不必要的:

#include <boost/thread/thread.hpp>
#include <iostream>

void FreeFunction()
{
  std::cout << "hello from free function" << std::endl;
}

struct SomeClass
{
  void MemberFunction()
  {
    std::cout << "hello from member function" << std::endl;
  }

  static void StaticFunction()
  {
    std::cout << "hello from static member function" << std::endl;
  }
};

int main()
{
  SomeClass someClass;

  // this free function will be used internally as is
  boost::thread t1(&FreeFunction);
  t1.join();

  // this static member function will be used internally as is
  boost::thread t2(&SomeClass::StaticFunction);
  t2.join();

  // boost::bind will be called on this member function internally
  boost::thread t3(&SomeClass::MemberFunction, someClass);
  t3.join();
}

输出:

hello from free function
hello from static member function
hello from member function

构造函数中的内部绑定(bind)为您完成所有工作。

刚刚添加了一些关于每种函数类型会发生什么的额外注释。 (希望我已经正确阅读了源代码!)据我所知,在外部使用 boost::bind 不会导致它也加倍并在内部被调用,因为它将按原样传递。

关于c++ - 使用或不使用 boost::bind() 创建一个 boost::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13742648/

相关文章:

c++ - vector 中数据的均匀分布

c++ - 使用 boost::shared_ptr 重载构造函数

c++ - 每次使用不同的 fixture 多次执行一个测试用例

C++线程问题——设置一个值表示线程已经结束

c++ - Boost asio 无法在所有线程上运行 io 服务。io 服务在第一个线程调用时阻塞

java - 通过 JNI 执行 OpenCV native 函数的问题

c++ - 两个类的前向声明会导致构造函数中的循环依赖吗?

c++ - 带有谷歌时间戳的 Protobuf C++ 消息导致段错误

c++ 内存泄漏 - boost 库

multithreading - 使用 Qt 增强 asio