boost thread on interruption doesn't print exit message

偶尔善良 提交于 2019-12-24 01:58:20

问题


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.



来源:https://stackoverflow.com/questions/19039675/boost-thread-on-interruption-doesnt-print-exit-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!