使用方法首先給信號量初始化賦值,可以根據需要設定需要的值,之前在寫項目的過程中用這個控制下載的線程個數。
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 }