boost信号量 boost::interprocess::interprocess_semaphore的用法
使用方法首先给信号量初始化赋值,可以根据需要设定需要的值,之前在写项目的过程中用这个控制下载的线程个数。
1 boost::interprocess::interprocess_semaphore m_semaphore(0);
然后就是pv操作了,v操作就只有一个post(),post()一次,信号量加1.p操作有三个,看函数名字都很明显知道是什么意思,
wait(),try_wait() ,timed_wait(const boost::posix_time::ptime&abs_time).
这里需要注意的是第三个p操做,对boost也不太熟, 很明显是等待到某一时间点,m_semaphore.timed_wait(boost::posix_time::ptime(second_clock::universal_time()+boost::posix_time::seconds(1))),等待一秒;这个时间是取universal_time,一开始不知道,试了几次不行,后面灵机一动看了下源码,原来如此.
1 inline bool interprocess_semaphore::timed_wait(const boost::posix_time::ptime &abs_time) 2 { 3 if(abs_time == boost::posix_time::pos_infin){ 4 this->wait(); 5 return true; 6 } 7 //Obtain current count and target time 8 boost::posix_time::ptime now(microsec_clock::universal_time()); 9 if(now >= abs_time) 10 return false; 11 12 do{ 13 if(this->try_wait()){ 14 break; 15 } 16 now = microsec_clock::universal_time(); 17 18 if(now >= abs_time){ 19 return this->try_wait(); 20 } 21 // relinquish current time slice 22 detail::thread_yield(); 23 }while (true); 24 return true; 25 }
下面举个栗子
1 #include <boost/interprocess/sync/interprocess_semaphore.hpp> 2 #include <boost/thread.hpp> 3 #include <boost/bind.hpp> 4 #include <boost/date_time/posix_time/posix_time.hpp> 5 #include <iostream> 6 using namespace std; 7 boost::interprocess::interprocess_semaphore m_semaphore(1); 8 void test(int i) 9 { 10 while(true) 11 { 12 if(m_semaphore.try_wait()) 13 { 14 printf("%d\n",i); 15 m_semaphore.post(); 16 17 } 18 boost::this_thread::sleep(boost::posix_time::seconds(2)); 19 20 } 21 } 22 using namespace boost::posix_time; 23 int main() 24 { 25 boost::thread thread1(boost::bind(&test,1)); 26 boost::thread thread2(boost::bind(&test,2)); 27 getchar(); 28 29 }