简体   繁体   中英

Instantiate threads without running them?

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

produces:

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

I'm aware this is caused by the C++ requirement to declare PrinterT outside of an if block, what I don't know how to do is how do I declare PrinterT without causing it to automatically execute the function code in the thread? I want to be able to make the running of the Printer function contingent on whether it's enabled or not.

std::thread has an operator = that will do the trick. It moves a running thread into another thread variable.

The default constructor will create a std::thread variable that isn't really a thread.

Try something like:

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

Yes, use default std::thread constructor and move semantics.

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

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

Example:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM