Boost logo

Boost Users :

From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2008-07-11 09:13:53

"Khandelwal, Amit" <amit.khandelwal_at_[hidden]> writes:

> 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.

> template <typename T, typename SEQUENCE = std::deque<T> >
> class tsqueue {
> const T& front() {
> boost::lock_guard<boost::mutex> lock(mutex);
> std::cout << "Pop element: " << m_queue.front() <<
> std::endl;
> return m_queue.front();
> }
> void pop() {
> boost::lock_guard<boost::mutex> lock(mutex);
> return m_queue.pop();
> }

This code is not thread safe unless there is only one consumer. Though
each operation is safe, the front()/pop() model gives you a race
condition: some other thread may steal your element between the call
to front() and pop().

for a description of a thread-safe queue that uses a condition
variable to provide waiting and allows multiple consumers.


Anthony Williams            | Just Software Solutions Ltd
Custom Software Development |
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at