> just want to know if std::queue empty() is thread safe (running on 2 or more
> thread)... so i can do,
[quoted text clipped - 5 lines]
> unlock()
> }
empty() may be thread safe by itself (I don't know), but this code
actually isn't. Consider the situation where queue isn't empty on "if"
but gets empty on "lock". To avoid this situation you must lock() before
querying the queue. If you are worrying about performance of
"unnecessary" lock then you have made two errors in judgment:
1. lock *is* necessary, and
2. performance loss is so minimal that we shouldn't even consider it.
Maybe in your case queue won't ever go from non-empty to empty between
"if" and "lock", because the code in the if branch is the only place
where this can happen. This shouldn't stop you from making robust code
that will work even when original assumptions are changed.
Jun - 04 Jul 2005 14:39 GMT
>> just want to know if std::queue empty() is thread safe (running on 2 or
>> more thread)... so i can do,
[quoted text clipped - 19 lines]
> this can happen. This shouldn't stop you from making robust code that will
> work even when original assumptions are changed.
oops... yeah got your point,
my bad i realize this after posting ~_~
thanks for your reply btw!
Doug Harrison [MVP] - 04 Jul 2005 17:37 GMT
>> just want to know if std::queue empty() is thread safe (running on 2 or more
>> thread)... so i can do,
[quoted text clipped - 7 lines]
>
> empty() may be thread safe by itself (I don't know)
It isn't. Note also that for the sequence above to have any chance of
working, lock/unlock would have to operate on the same mutex as std::queue
uses internally, if it used a mutex internally, which it doesn't.
> but this code
> actually isn't. Consider the situation where queue isn't empty on "if"
[quoted text clipped - 4 lines]
> 1. lock *is* necessary, and
> 2. performance loss is so minimal that we shouldn't even consider it.
Point (2) doesn't necessarily apply.
> Maybe in your case queue won't ever go from non-empty to empty between
> "if" and "lock", because the code in the if branch is the only place
> where this can happen. This shouldn't stop you from making robust code
> that will work even when original assumptions are changed.
Those "original assumptions" don't help. The code given above contains a
synchronization error no matter how you look at it.

Signature
Doug Harrison
Microsoft MVP - Visual C++
I think that most the containers provided by MFC are all not threadsafe,
you must synchronize your manipulations by yourself.