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而不导致它在线程中自动执行功能代码?我希望能够使打印机功能的运行取决于是否启用该功能。

最佳答案

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();}

10-07 22:44