views:

839

answers:

5

I have a thread push-backing to STL list and another thread pop-fronting from the list. Do I need to lock the list with mutex in such case?

+1  A: 

Probably. These operations are not simple enough to be atomic, so they'll only be thread-safe if the implementation explicitly performs the necessary locking.

However, the C++ standard does not specify whether these operations should be thread-safe, so it is up to the individual implementation to decide that. Check the docs. (Or let us know which implementation you're using)

jalf
+1  A: 

There is no guarantee that a STL implementation is thread-safe, and since it costs performance I would guess that most aren't. You should definitely use a mutex.

mghie
+1  A: 

Since the stl pop / push operations are AFAIK non-atomic you do have to use a mutex.

Adrian Grigore
+11  A: 

From SGI's STL on Thread Safety:

If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

Since both your threads modify the list, I guess you have to lock it.

João da Silva
SGI's STL is not the same as the STL-alike implemented in the C++ standard library. The latter says nothing about concurrency or threading. (There are a number of other differences as well, though these aren't relevant here). But in short, you can't assume that what SGI says will apply to the stdlib
jalf
+2  A: 

Most STL implementations are thread safe in the sens that you can access several instances of a list type from several threads without locking. But you MUST lock when you are accessing the same instance of your list.

Have a look on this for more informations : thread safty in sgi stl

Ben