Re: std::deque Thread Saftey Situtation
On Aug 30, 7:06 pm, Jerry Coffin <jcof...@taeus.com> wrote:
In article <0bbce4f3-4ab7-47fd-8be1-
7d1b39e7f...@n38g2000prl.googlegroups.com>, nvr...@gmail.com says...
I've read a bit online seeing that two writes are not safe, which I
understand, but would 1 thread push()'ing and 1 thread pop()'ing be
thread-safe? Basically my situation is the follows:
Generally speaking, no, it's not safe.
My advice would be to avoid std::deque in such a situation --
in a multi-threaded situation, it places an undue burden on
the client code.
Avoid it, or wrap it? I use it regularly for communicating
between threads; my Queue class is based on it.
This is a case where it's quite reasonable to incorporate the
locking into the data structure itself to simplify the client
code (a lot).
For one example, I've used code like this under Windows for
quite a while:
template<class T, unsigned max = 256>
class queue {
HANDLE space_avail; // signaled => at least one slot empty
HANDLE data_avail; // signaled => at least one slot full
CRITICAL_SECTION mutex; // protect buffer, in_pos, out_pos
T buffer[max];
long in_pos, out_pos;
And if you replace buffer, in_pos and out_pos with
std::deque<T>, where's the problem.
[...]
Exception safety depends on assignment of T being nothrow, but
(IIRC) not much else is needed. This uses value semantics, so
if you're dealing with something where copying is expensive,
you're expected to use some sort of smart pointer to avoid
copying. Of course, a reference counted smart pointer will
usually have some locking of its own on incrementing and
decrementing the reference count, but that's a separate issue.
My own queues use std::auto_ptr at the interface. This imposes
the requirement that all of the contained objects be dynamically
allocated, and adds some clean-up code in the queue itself
(since you can't put the auto_ptr in the deque), but ensures
that once the message has been posted, the originating thread
won't continue to access it.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34