boost信号量 boost::interprocess::interprocess_semaphore的用法

时间:2021-10-04 23:41:55

使用方法首先给信号量初始化赋值,可以根据需要设定需要的值,之前在写项目的过程中用这个控制下载的线程个数。

 boost::interprocess::interprocess_semaphore m_semaphore();

然后就是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,一开始不知道,试了几次不行,后面灵机一动看了下源码,原来如此.

 inline bool interprocess_semaphore::timed_wait(const boost::posix_time::ptime &abs_time)
{
if(abs_time == boost::posix_time::pos_infin){
this->wait();
return true;
}
//Obtain current count and target time
boost::posix_time::ptime now(microsec_clock::universal_time());
if(now >= abs_time)
return false; do{
if(this->try_wait()){
break;
}
now = microsec_clock::universal_time(); if(now >= abs_time){
return this->try_wait();
}
// relinquish current time slice
detail::thread_yield();
}while (true);
return true;
}

下面举个栗子

 #include <boost/interprocess/sync/interprocess_semaphore.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
using namespace std;
boost::interprocess::interprocess_semaphore m_semaphore();
void test(int i)
{
while(true)
{
if(m_semaphore.try_wait())
{
printf("%d\n",i);
m_semaphore.post(); }
boost::this_thread::sleep(boost::posix_time::seconds()); }
}
using namespace boost::posix_time;
int main()
{
boost::thread thread1(boost::bind(&test,));
boost::thread thread2(boost::bind(&test,));
getchar(); }