Khandelwal, Amit wrote:
The way I use mutex is to protect one shared resource. Here is sample code that I cooked up. I am not sure why you want to use a single mutex to protect multiple resources. However, if your use case demands it than wrap those resources in a class and have a mutex as a member variable of that class.
HTH.
Call this file let say ThreadSafeQueue.hpp
#include
#include <iostream> #include <queue> #include <deque> namespace std { namespace threadsafe {
template
class tsqueue { private: std::queue
m_queue; boost::mutex mutex; public:
[snip]
const T& front() { boost::lock_guardboost::mutex lock(mutex); std::cout << "Pop element: " << m_queue.front() << std::endl; return m_queue.front(); }
Ouch. Returning an element by reference could easily lead to trouble when the container is accessed from multiple threads. / Johan