boost 条件变量
1 // boost 条件变量 2 // 做个简单的笔记 3 4 #include <boost/thread/mutex.hpp> 5 #include <boost/thread/condition.hpp> 6 7 8 boost::mutex m_mutex; 9 boost::condition_variable_any m_cond_var; 10 11 12 // 加锁 13 do 14 { 15 boost::mutex::scoped_lock Lock(m_mutex); 16 // other doing 17 } 18 while (false); 19 // 唤醒沉睡的线程 20 m_cond_var.notify_all(); 21 22 23 24 // 进入条件变量沉睡,直到通知的到来。 25 // 调用wait 之前必须加锁成功 26 // 因为在wait() 中会首先释放锁。 27 // 同时,当wait() 函数返回后,该函数会将锁拿到, 28 // 所以wait() 函数返回后,是持有该锁的状态返回的。 29 m_mutex.lock(); 30 m_cond_var.wait(m_mutex); 31 m_mutex.unlock(); 32 33 // 定时休眠 34 { 35 boost::mutex::scoped_lock lk(m_mutex); 36 if (m_cond_var.timed_wait( 37 lk, get_system_time() + posix_time::seconds(1))) 38 { 39 线程被 notify 唤醒 40 } 41 else 42 { 43 超时 44 } 45 } 46 47 // 消费者线程使用条件变量 48 void Consumer() 49 { 50 while (true) 51 { 52 { 53 boost::mutex::scoped_lock lk(m_mutex); 54 // 每次进入条件变量休眠之前都要判断是否满足条件进入条件变量。 55 // 这一步很容易忘记 56 while (满足进入条件变量的条件) 57 m_cond_var.wait(lk); 58 // 从集合中提取需要的数据 59 // 块结束,lk 会自动释放锁 60 } 61 62 ... // 处理从集合中得到的数据 63 } 64 }