|
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().
See
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
for a description of a thread-safe queue that uses a condition
variable to provide waiting and allows multiple consumers.
Anthony
-- Anthony Williams | Just Software Solutions Ltd Custom Software Development | http://www.justsoftwaresolutions.co.uk Registered in England, Company Number 5478976. Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL
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