I have need of a semaphore, but I have been unable to find any good ones on the web, only some source.
So I modified the source to roll out my own simplistic semaphore, and thus I'd like for some other people to look it over and see that I haven't done something stupid.
If you know of a good (and fast!) semaphore out there already, I'd also be interested.
Code:#include <boost/thread/condition_variable.hpp> #include <boost/thread/mutex.hpp> #include <tbb/atomic.h> class XSemaphore { //The current semaphore count. tbb::atomic<unsigned int> m_count; //mutex_ protects count_. //Any code that reads or writes the count_ data must hold a lock on //the mutex. boost::mutex m_mutex; //Code that increments count_ must notify the condition variable. boost::condition_variable m_condition; public: explicit XSemaphore(unsigned int initial_count) { m_count = initial_count; } unsigned int get_count() const //for debugging/testing only { //The "lock" object locks the mutex when it's constructed, //and unlocks it when it's destroyed. //boost::unique_lock<boost::mutex> lock(mutex_); return m_count; } void signal() //called "release" in Java { ++m_count; //Wake up any waiting threads. //Always do this, even if count_ wasn't 0 on entry. //Otherwise, we might not wake up enough waiting threads if we //get a number of signal() calls in a row. m_condition.notify_one(); } void wait() //called "acquire" in Java { while (m_count == 0) { boost::unique_lock<boost::mutex> lock(m_mutex); m_condition.wait(lock); } --m_count; } };



LinkBack URL
About LinkBacks



