[Assorted-commits] SF.net SVN: assorted:[1345] cpp-commons/trunk/src/commons/squeue.h
Brought to you by:
yangzhang
From: <yan...@us...> - 2009-04-29 02:07:23
|
Revision: 1345 http://assorted.svn.sourceforge.net/assorted/?rev=1345&view=rev Author: yangzhang Date: 2009-04-29 02:07:06 +0000 (Wed, 29 Apr 2009) Log Message: ----------- added synchronized queue Added Paths: ----------- cpp-commons/trunk/src/commons/squeue.h Added: cpp-commons/trunk/src/commons/squeue.h =================================================================== --- cpp-commons/trunk/src/commons/squeue.h (rev 0) +++ cpp-commons/trunk/src/commons/squeue.h 2009-04-29 02:07:06 UTC (rev 1345) @@ -0,0 +1,63 @@ +#ifndef COMMONS_SQUEUE_H +#define COMMONS_SQUEUE_H + +#include <queue> +#include <boost/thread/mutex.hpp> +#include <boost/thread/condition_variable.hpp> + +namespace commons +{ + using namespace std; + using namespace boost; + + template<typename T> + class concurrent_queue + { + private: + queue<T> q_; + mutable mutex m_; + condition_variable c_; + + public: + template<typename U> void push(U &&x) + { + mutex::scoped_lock lock(m_); + q_.push(forward<U>(x)); + lock.unlock(); + c_.notify_one(); + } + + bool empty() const + { + mutex::scoped_lock lock(m_); + return q_.empty(); + } + + bool try_pop(T& x) + { + mutex::scoped_lock lock(m_); + if (q_.empty()) return false; + x = q_.front(); + q_.pop(); + return true; + } + + void pop(T& x) + { + mutex::scoped_lock lock(m_); + while (q_.empty()) c_.wait(lock); + x = move(q_.front()); + q_.pop(); + } + + T take() { + mutex::scoped_lock lock(m_); + while (q_.empty()) c_.wait(lock); + T x = move(q_.front()); + q_.pop(); + return x; + } + }; +} + +#endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |