中断时提升线程不会打印退出消息

时间:2013-09-26 22:19:45

标签: c++ multithreading boost boost-thread interruption

我有这段代码用于执行三个线程,其中第二个线程应该在按Enter键时被中断并打印退出消息:

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

process_thread在“ENTER”上中断,但不打印“退出进程线程消息”。任何人都可以建议问题是什么,因为我昨天有一个类似的程序正常运行。 提前致谢!

1 个答案:

答案 0 :(得分:2)

运行process_val的线程正在休眠200ms,因此除非您在程序启动后按下一个小于200ms的密钥,否则该线程已经返回并且try / catch不再有效。如果你将睡眠时间增加到几千毫秒,你应该有时间在等待时按一下键。

相关问题