实例化线程而不运行它们?

时间:2014-03-24 23:06:50

标签: c++ multithreading

enablePrint = (bool)someArgv; //set via argv in some code, don't worry about this

if (enablePrint) {
    std::thread PrinterT(&Printer, 1000);}
//some code that does some stuff
if (enablePrint) {
    PrinterT.join();}

产生

compile error 194:9: error: ‘PrinterT’ was not declared in this scope PrinterT.join();}

我知道这是由C ++要求在if块之外声明PrinterT引起的,我不知道该怎么做才是如何声明PrinterT而不会导致它自动执行该功能线程中的代码?我希望能够使打印机功能的运行取决于它是否启用。

2 个答案:

答案 0 :(得分:1)

std :: thread有一个operator =可以解决问题。它将正在运行的线程移动到另一个线程变量中。

默认构造函数将创建一个不是线程的std :: thread变量。

尝试类似:

enablePrint = (bool)someArgv; //set via argv in some code, don't worry about this

std::thread PrinterT;
if (enablePrint) {
    PrinterT = std::thread(&Printer, 1000);}

//some code that does some stuff
if (enablePrint) {
    PrinterT.join();}

答案 1 :(得分:0)

是的,使用默认的std::thread构造函数并移动语义。

thread()http://ru.cppreference.com/w/cpp/thread/thread/thread

operator=(thread&&)http://en.cppreference.com/w/cpp/thread/thread/operator%3D

示例:

#include <iostream>
#include <thread>

int main() {
    bool flag = true;
    std::thread thread;

    if (flag) {
        thread = std::thread([]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(5000));
            std::cout << "Thread done\n";
        });
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    std::cout << "Main done\n";

    if (flag) {
        thread.join();
    }
    return 0;
}