正在初始化可移动类的ctor中的std::thread

Initializing std::thread in ctor of movable class

本文关键字:中的 std ctor thread 初始化 可移动      更新时间:2023-10-16

我需要在类的ctor中初始化一个std::线程。线程应该运行类本身的成员函数。在ctor中,当尝试初始化线程时,程序会尝试运行成员函数。(实现了Move语义)。

Page::Page(Motion *_parent):
    parent(_parent)
{
    std::thread x(&Page::play,this);
    starter = std::move(x);
}

程序运行thisplay()

编辑:我这样做:

void Page::start()
{
    std::thread x(&Page::play,this);
    x.join();
}

效果很好,但不知道是否可以。。。现在我正在使用std::bind,如果这是标准的操作方式,我将替换代码。

std::thread的构造函数会立即自动启动线程,然后新线程会调用所提供的函数,因此

std::thread x(&Page::play,this);

在新线程上自动调用CCD_ 5。

这与某些线程库(如.Net)不同,在某些线程库中,必须通过调用Start()成员函数来显式启动线程。std::thread不存在"延迟启动"功能。

如果在调用其他函数之前不希望线程真正启动,请不要在构造函数中初始化std::thread对象,而是在start()函数中初始化,如图所示。

如果在线程对象上调用join(),那么代码将等待线程在调用join()时完成。因此,如果像在示例start()函数中那样,在构造线程对象之后立即放置联接,那么您还不如直接调用play(),因为start()在线程完成之前不会返回。

您不需要std::bindstd::thread——线程构造函数会自动处理绑定。

这样的东西怎么样:

#include <iostream>
#include <thread>
#include <functional>
struct Foo
{
    Foo()
        : thread(std::bind(Foo::bar, this))        
        { }
    ~Foo() 
        { thread.join(); }
    static void bar(Foo *foo)
        { }
    std::thread thread;
};
int main()
{
    Foo foo;
}