Use the method first to give the semaphore initialization assignment, you can set the desired value as needed, before writing the project in the process of using this control to download the number of threads.
1 boost::interprocess::interprocess_semaphore M_semaphore (0);
Then is the PV operation, v operation only one post (), post () once, the semaphore plus 1.P operation has three, see the function name is clearly know what meaning,
Wait (), try_wait (), timed_wait (const boost::p osix_time::p time&abs_time).
It is important to note that the third p is not well-acquainted with boost, and is obviously waiting for a point in time, m_semaphore.timed_wait (boost::p osix_time::p Times (second_clock::universal _time () +boost::p osix_time::seconds (1)), wait a second, this time is to take universal_time, at the beginning do not know, tried a few times not, behind Brainwave read the next source, so.
1InlineBOOLInterprocess_semaphore::timed_wait (ConstBoost::p osix_time::p Time &abs_time)2 {3 if(Abs_time = =boost::p osix_time::p os_infin) {4 This-wait ();5 return true;6 }7 //obtain current count and target time8 boost::p osix_time::p Time Now (Microsec_clock::universal_time ());9 if(Now >=abs_time)Ten return false; One A Do{ - if( This-try_wait ()) { - Break; the } -now =microsec_clock::universal_time (); - - if(Now >=abs_time) { + return This-try_wait (); - } + //Relinquish Current time slice A Detail::thread_yield (); at} while(true); - return true; -}
Here's a chestnut.
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 namespacestd;7Boost::interprocess::interprocess_semaphore M_semaphore (1);8 voidTestinti)9 {Ten while(true) One { A if(M_semaphore.try_wait ()) - { -printf"%d\n", i); the m_semaphore.post (); - - } -Boost::this_thread::sleep (boost::p osix_time::seconds (2)); + - } + } A using namespaceboost::p osix_time; at intMain () - { -Boost::thread Thread1 (Boost::bind (&test,1)); -Boost::thread thread2 (Boost::bind (&test,2)); - GetChar (); - in}
The use of Boost signal volume Boost::interprocess::interprocess_semaphore