두 스레드로 condition_variable
을 구현하려고 시도했지만 사용자 입력 (std::cin
)을 사용하지 않으면 다음 코드가 제대로 작동하지만 일단 사용한 후에는 숫자를 입력 한 후 프로그램이 다운 됨 화면에.C++ condition_variable cin 및 cout
왜 충돌이 발생합니까?
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;
}
사이드 정보 :'std :: condition_variable'은 "허위 깨우기"를 유발할 수 있으므로'cond_wait (locker);'는 th_in이'cond.notify_all();'을 호출하지 않을 때 차단 해제됩니다. [std :: condition_variable] (http://en.cppreference.com/w/cpp/thread/condition_variable)도 참조하십시오. – yohjp