c++ - boost线程在中断时不打印退出消息

标签 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”时中断,但未打印“退出进程线程消息”。任何人都可以建议问题可能是什么,因为我昨天有一个类似的程序正常运行。 提前致谢!

最佳答案

运行process_val的线程只休眠了200ms,所以除非你能在程序启动后200ms以内按下一个键,否则该线程已经返回并且try/catch不再有效。如果您将 sleep 时间增加到几千毫秒,您应该有时间在等待时按键。

关于c++ - boost线程在中断时不打印退出消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039675/

相关文章:

c++ - 在 C++ 中,什么时候传递指针优于传递引用?

multithreading - Perl 模块 ForkManager 不工作

windows - QueryPerformanceCounter 和线程安全

java - ThreadPoolExecutor$Worker 中的奇怪代码

c++ - 使用boost库更新具有相同名称的每个节点的XML属性值时出现的问题

c++ - Boost Mini C 教程

c++ - 为什么共享锁只能持有一把可升级锁

c++ - C++获取构造函数的类型

c++ - C++ Cmake的OpenCV

c++ - C++ 中的多态返回类型