C ++ condition_variable cin和cout

时间:2013-07-18 21:33:22

标签: c++ c++11 concurrency iostream

我尝试使用两个线程实现condition_variable,如果我不使用用户输入(std::cin),以下代码将会正常工作,但是一旦我使用它,程序在我之后崩溃了在屏幕上输入一个数字。

为什么会崩溃?

std::mutex mu;
std::condition_variable cond;
int x =0;
void th_in()
{
  std::unique_lock <mutex> locker(mu);
  std::cin>>x;
  locker.unlock();
  cond.notify_all();
}
void th_out()
{
  std::unique_lock <mutex> locker(mu);
  cond.wait(locker);
  std::cout<<x<<std::endl;
  locker.unlock();
}

int main()
{    
  std::thread t2(th_out);
  std::thread t1(th_in);    
  std::cin.get();
  return 0;
}

1 个答案:

答案 0 :(得分:5)

这种情况正在发生,因为当您提供输入(std::cin.get())并且您没有分离线程或加入它们时,您的程序正在退出。

Anthony Williams行动并发中,声明必须在std::thread::join对象被销毁之前显式调用std::thread::detachstd::thread ,否则将调用std::terminate

因此,崩溃。


您可以通过让int main等待线程完成执行来修复它:

int main() {
    std::thread t2(th_out);
    std::thread t1(th_in);

    t2.join();
    t1.join();

    std::cin.get();
    return 0;
}

这应该更安全。这也解决了由std::cin阻止2个线程调用的问题。

相关问题