2013-06-11 3 views
0

뮤텍스가없는 스레드를 동기화하는 올바른 방법입니까? 이 코드는 당신이 뭘하려는 건지 정확히 모른 채 오랜 시간이것은 올바른 뮤텍스와 동기화를 수행하는 방법입니까?

#include <boost/thread.hpp> 
#include <boost/thread/mutex.hpp> 
#include <boost/memory_order.hpp> 
#include <atomic> 

std::atomic<long> x =0; 
std::atomic<long> y =0; 

boost::mutex m1; 

// Thread increments 
void Thread_Func() 
{ 
    for(;;) 
    { 
//  boost::mutex::scoped_lock lx(m1); 
     ++x; 
     ++y; 
    } 
} 

// Checker Thread 
void Thread_Func_X() 
{ 
    for(;;) 
    { 
//  boost::mutex::scoped_lock lx(m1); 
     if(y > x) 
     { 
// should never hit until int overflows 
      std::cout << y << "\\" << x << std::endl; 
      break; 
     } 
    } 
} 

//Test Application 
int main(int argc, char* argv[]) 
{ 
    boost::thread_group threads; 
    threads.create_thread(Thread_Func); 
    threads.create_thread(Thread_Func_X); 
    threads.join_all(); 
    return 0; 
} 

답변

0

에 출마해야한다,이 "올바른"방법이라고하기 어렵다. 그게 유효한 코드예요, 조금 janky예요.

"검사기"스레드에서 조건 y > x이 표시된다는 보장은 없습니다. 이론적으로 결코 깨지지 않을 가능성이 있습니다. 실제로는 어떤 시점에서 트리거되지만 x는 LONG_MIN 및 y LONG_MAX가 아닐 수 있습니다. 즉, 오버플로가 발생하는 것처럼 트리거하는 것은 보장되지 않습니다.