Boost logo

Boost Users :

From: Johan Nilsson (r.johan.nilsson_at_[hidden])
Date: 2008-07-11 09:41:41


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 <boost/thread.hpp>
> #include <iostream>
> #include <queue>
> #include <deque>
>
> namespace std {
> namespace threadsafe {
>
> template <typename T, typename SEQUENCE = std::deque<T> >
> class tsqueue {
>
> private:
> std::queue<T, SEQUENCE> m_queue;
> boost::mutex mutex;
>
> public:

[snip]

> const T& front() {
> boost::lock_guard<boost::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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net