I am currently designing a synchronized queue used to communicate between threads. Is this the code given below a good solution? Am I using mutex lock/unlock more than needed?
Are there any resources out there on the Internet for thread-safe data- structures? /Nordlöw The file synched_queue.hpp follows: #ifndef PNW__SYNCHED_QUEUE_HPP #define PNW__SYNCHED_QUEUE_HPP /*! * @file synched_queue.hpp * @brief Synchronized (Thread Safe) Container Wrapper on std:queue * using Boost::Thread. */ #include <queue> #include <iostream> #include <boost/bind.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> // ============================================================================ template <typename T> class synched_queue { std::queue<T> q; ///< Queue. boost::mutex m; ///< Mutex. public: /*! * Push @p value. */ void push(const T & value) { boost::mutex::scoped_lock sl(m); // NOTE: lock mutex q.push(value); } /*! * Try and pop into @p value, returning directly in any case. * @return true if pop was success, false otherwise. */ bool try_pop(T & value) { boost::mutex::scoped_lock sl(m); // NOTE: lock mutex if (q.size()) { value = q.front(); q.pop(); return true; } return false; } /// Pop and return value, possibly waiting forever. T wait_pop() { boost::mutex::scoped_lock sl(m); // NOTE: lock mutex // wait until queue has at least on element() c.wait(sl, boost::bind(&std::queue<T>::size, q)); T value = q.front(); q.pop(); return value; } size_type size() const { boost::mutex::scoped_lock sl(m); // NOTE: lock mutex return q.size(); } bool empty() const { boost::mutex::scoped_lock sl(m); // NOTE: lock mutex return q.empty(); } }; // ============================================================================ #endif _______________________________________________ help-gplusplus mailing list help-gplusplus@gnu.org http://lists.gnu.org/mailman/listinfo/help-gplusplus