Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to lock STL list with mutex in push_back pop_front scenario?

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?

like image 557
jackhab Avatar asked Feb 05 '09 11:02

jackhab


3 Answers

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.

like image 51
Joao da Silva Avatar answered Oct 14 '22 21:10

Joao da Silva


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

like image 28
Ben Avatar answered Oct 14 '22 21:10

Ben


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)

like image 42
jalf Avatar answered Oct 14 '22 21:10

jalf