【问题标题】:running std::thread not in Constructor不在构造函数中运行 std::thread
【发布时间】:2018-06-30 16:59:16
【问题描述】:

我想了解如何使用std::thread。大多数std::thread 教程都是这样的

void foo() { ... }
....
std::thread thread(foo);
....
thread.join();

好的,我知道我们可以在构造函数中指定附加到线程的函数。但是,我们还有其他办法吗?

换句话说,我需要插入什么来运行t3线程?

#include <thread>
#include <iostream>

void print(const char* s){
    while (true)
        std::cout << s <<'\n';
}

int main() {

    std::thread t1(print, "foo");
    std::thread *t2;
    t2 = new std::thread(print, "bar");
    std::thread t3; // Don't change this line
    // what I need to put here to run t3 ?

    t1.join();
    t2->join();
    t3.join();
    delete t2;
    return 0;
}

【问题讨论】:

    标签: c++ std stdthread


    【解决方案1】:

    t3 本质上是一个虚拟线程。查看默认构造函数的引用:

    创建不代表线程的新线程对象。

    但由于std::thread 具有operator=(std::thread&amp;&amp;),您可以通过将新线程移动到变量中来使其代表实际线程:

    t3 = std::thread(print, "foobar");
    

    这将创建并启动一个新线程,然后将其分配给t3

    【讨论】:

    • 在这种情况下,“使用”或“不使用”std::move 之间的实际区别是什么?
    • 其实是多余的。但是我正在查看文档并试图避免调用复制构造函数,所以为了安全起见,我只输入了std::move
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多