Re: using std::queue with two threads
hongseok.yoon@gmail.com wrote:
I've two threads and one thread only write to std::queue using push()
function and another thread only read from std::queue using front()
and pop() functions.
If I suppose to use no mutex, is the queue thread-safe?
No. Note that multithreading is not only about atomicity (i.e. that you
don't read things while they are temporarily inconsistent) and mutuality
(i.e. that no two writes take place at the same time) but also about
visibility (i.e. that you either see all or nothing from a former write
operation in another thread). The latter case might easily not be
guaranteed, in particular when the other thread is running on a different
CPU. Another problem would be e.g. a size counter which needs to be written
by both sides.
A totally different problem might be the underlying container which might
have to reallocate its buffers and thus move existing elements which are
accessed by a different thread. This depends on the container though, I
think the default deque<> is safe in that aspect.
Disclaimer: the C++ standard is totally silent about threads, so nothing is
guaranteed to be portable.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]