gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:44 24 4
gpt4 key购买 nike

我正在尝试构造一个 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/31610611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com