Boost logo

Boost :

From: Vladimir Prus (ghost_at_[hidden])
Date: 2004-02-13 03:15:49


Raoul Gough wrote:

>> - thread-safe queue (no immediate need, but is likely to arise in future)
>
> I implemented a thread-safe queue on top of Boost.Threads about 18
> months ago. It has a locking proxy that provides access to the raw
> container, as well as providing block-on-empty and block-on-full
> operations. e.g.
>
> // typedef mt::safe_queue<std::deque<Element> > queue_type;
> // queue_type *g_queue_ptr;
>
> {
> queue_type::proxy_type const &proxy (g_queue_ptr->get_proxy());
> // Locks mutex. Noncompliant because scoped_lock is noncopyable
> // but works on gcc at least. This could be made compliant e.g.
> // using shared_ptr<proxy_type>

Hmm.. I don't see scoped_ptr anywhere in the example?

> proxy.block_while_empty (timeout);
> // Uses timed_wait (temporarily releases lock)
>
> while (!proxy->empty()) // Accesses raw container
> {
> // ...
> proxy->pop_front(); // Accesses raw container
> }

I guess proxy's operator-> locks the mutex. Hmm... what happens if

1. The proxy->empty() returns false.
2. Another thread, using the fact that mutex is not locked now, extracts all
the elements from queue.
3. The first thread executes proxy->pop_front()

I might be missing something, but is wrapping of all operation in mutex
(i.e. making them synchronized in Java-speak), makes the resulting
container sufficiently safe?

- Volodya


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk