【问题标题】:boost thread on interruption doesn't print exit message中断时提升线程不打印退出消息
【发布时间】:2013-10-03 02:19:10
【问题描述】:

我有这段代码用于执行三个线程,其中第二个线程应该在按下 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”时被中断,但没有打印“退出进程线程消息”。任何人都可以提出问题可能是什么,因为我昨天有一个类似的程序正常运行。 提前致谢!

【问题讨论】:

  • 对我有用,如果我将超时时间增加到 2000 毫秒。编译器、平台、版本?
  • 旁注: cin.get(key_pressed); 在这种情况下,cin.ignore(); 应该足够了,因为您不使用输入。

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


【解决方案1】:

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

【讨论】:

  • 啊.. 这很明显!非常感谢您回答这么愚蠢的问题。我只是不专心。
猜你喜欢
  • 1970-01-01
  • 2021-03-12
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2017-03-04
  • 2022-01-19
相关资源
最近更新 更多