2013-07-18 2 views
2

두 스레드로 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; 
} 
+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

답변

5

이것은 당신이 입력 (std::cin.get())을 줄 때 프로그램이 종료되고 당신이 스레드를 분리하지 않거나 그들에 합류하기 때문에 일어나고있다. Anthony Williams 액션에 동시성에서

, std::thread 개체가 소멸되기 전에 std::thread::join 또는 std::thread::detach이 다른 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; 
} 

이 안전해야한다. 이는 또한 2 개의 스레드가 std::cin에 의해 차단되어 발생하는 문제를 해결합니다.