2012-10-19 23 views
1

我是Boost編程中的新手。我想要做的是從main()中創建一個線程,它將持續運行,直到main()退出。現在,我正在對該線程執行一些操作,當它完成時,它將設置一個布爾標誌。 main()將等待這個標誌被設置,當它爲'true'時,main()將完成它的工作,重置標誌並等待它再次被設置。另一個線程將連續運行。在助推線程中讀標誌

任何人都可以提供一套簡單的boost線程指令來實現這個目標嗎?

我試圖做到這一點的僞

class Call { 
public: 
    bool flag, do_it; 
    keyboard_callback() { 
     if('s' pressed) do_it = true; 
    } 
    f() { // some callback function 
     if(do_it == true) flag=true; 
    } 
    void func() { 
     ...register callback f() 
     ...register keyboard_callback() 
     ... 
     while(some condition) { keep running , exit when 'q'} 
     ... 
    } 
}; 
main() 
{ 
    Call obj; 
    boost::thread th (boost::bind(&Call::func, &obj)); 
    th.detach(); 
    while(true) { 
     while (obj.flag == false); 
     ...do something 
    } 
} 

回答

0
// shared variables 
boost::mutex mutex; 
boost::condition_variable condition; 
bool flag = false; 

// signal completion 
boost::unique_lock<boost::mutex> lock(mutex); 
flag = true; 
condition.notify_one(); 

// waiting in main method 
boost::unique_lock<boost::mutex> lock(mutex); 
while (!flag) { 
    condition.wait(lock); 
} 
+0

謝謝!有效! – DonaldS