c++ - 以成员函数启动线程

标签 c++ multithreading c++11

我正在尝试构造一个 std::thread,其成员函数不接受任何参数并返回 void。我想不出任何有效的语法——编译器无论如何都会提示。实现 spawn() 以返回执行 test()std::thread 的正确方法是什么?

#include <thread>
class blub {
  void test() {
  }
public:
  std::thread spawn() {
    return { test };
  }
};

最佳答案

#include <thread>
#include <iostream>

class bar {
public:
  void foo() {
    std::cout << "hello from member function" << std::endl;
  }
};

int main()
{
  std::thread t(&bar::foo, bar());
  t.join();
}

编辑: 考虑到您的编辑,您必须这样做:

  std::thread spawn() {
    return std::thread(&blub::test, this);
  }

更新:我想再解释一些要点,其中一些也已在评论中讨论过。

上述语法是根据 INVOKE 定义 (§20.8.2.1) 定义的:

Define INVOKE (f, t1, t2, ..., tN) as follows:

  • (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;
  • ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;
  • t1.*f when N == 1 and f is a pointer to member data of a class T and t 1 is an object of type T or a
    reference to an object of type T or a reference to an object of a
    type derived from T;
  • (*t1).*f when N == 1 and f is a pointer to member data of a class T and t 1 is not one of the types described in the previous item;
  • f(t1, t2, ..., tN) in all other cases.

我想指出的另一个一般事实是,默认情况下,线程构造函数将复制传递给它的所有参数。这样做的原因是参数可能需要比调用线程长,复制参数可以保证这一点。相反,如果您想真正传递一个引用,您可以使用由 std::ref 创建的 std::reference_wrapper

std::thread (foo, std::ref(arg1));

通过这样做,您 promise 当线程对参数进行操作时,您将确保参数仍然存在。


请注意,上面提到的所有内容也可以应用于 std::asyncstd::bind

关于c++ - 以成员函数启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58588975/

相关文章:

c++ - 安装构建工具后找不到 Visual Studio Code MSVC cl.exe

c++ - 日期类型精度对性能的影响

c++ - operator new 可以在施工完成前返回吗?

java - 下面的代码不是线程安全的吗?

c++ - 如何管理 "shortest of"类型的生命周期?

c++ - 用于 c++11 线程的 RW 锁

c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序

使用指向同一类对象的指针的 C++ 类构造函数

multithreading - 对于多线程 http 下载应用程序,您选择的编程语言是什么?

c++ - 对于 boost io_service,是否只有一个线程在 epoll_wait 上阻塞?