boost thread on interruption doesn't print exi

2019-07-19 18:28发布

问题:

I have this piece of code for executing three threads where the second thread should get interrupted on pressing enter and print the exit message:

void input_val()
{
    // DO STUFF
return;
}

void process_val()
{
       // DO STUFF
       try{
        cout << "waiting for ENTER..." << endl;
        boost::this_thread::sleep(boost::posix_time::milliseconds(200));
    }
    catch(boost::thread_interrupted&){
        cout << "exit process thread" << endl;
        return;
    }
    return;
}


void output_val()
{
    // DO STUFF
}

int main()
{
    char key_pressed;

    boost::thread input_thread(boost::bind(&input_val));
    boost::thread process_thread(boost::bind(&process_val));
    boost::thread output_thread(boost::bind(&output_val));

    cin.get(key_pressed);
    process_thread.interrupt();

    input_thread.join();
    process_thread.join();
    output_thread.join();
    return 0;
}

The process_thread is interrupted on "ENTER" but is not printing the "exit process thread message". Can anyone suggest what the issue could be, because I got a similar program running properly yesterday. Thanks in advance!

回答1:

The thread running process_val is sleeping for only 200ms, so unless you can press a key less than 200ms after the program starts, that thread has already returned and the try/catch is no longer in effect. If you increase the sleep to a few thousand ms, you should have time to press a key while it's waiting.