Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which STL container has a thread-safe insertion process?

Which STL container has a thread safe insertion process? I want several threads to simultaneously insert in the same container. Any implementation other than STL (i.e., Boost) is welcome!

like image 544
Tarek Avatar asked Oct 29 '11 15:10

Tarek


People also ask

Which STL is thread safe?

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.

What are the various types of STL containers?

Types of STL Container in C++ In C++, there are generally 3 kinds of STL containers: Sequential Containers. Associative Containers. Unordered Associative Containers.

Is STD Vector empty thread safe?

There is no thread-safe guaranty on anything in the containers and algorithms of the the STL. So, No.


2 Answers

The STL containers are not thread safe. You have to impose that yourself, should you so wish, with your own synchronisation.

like image 183
David Heffernan Avatar answered Sep 27 '22 22:09

David Heffernan


I am trying to avoid the critical region in multi-threading because it deteriorates the performance !

On the contrary, it improves performance. Because the kind of locking a container class can do is only the very fine-grained kind, having to acquire the lock for each simple operation. That's expensive. When you take care of locking, you have the luxury of acquiring the lock and perform many operations. That does not improve the odds for concurrency but greatly reduces the locking overhead. You can choose the strategy that makes most sense for your app, it isn't forced on you.

Add to this that it is next to impossible to write a thread-safe container implementation that isn't either prone to deadlock or very expensive. Iterators are the problem. The library writer has to choose between taking a lock for the life time of the iterator (risking deadlock) or needs to update all live iterators when another thread changes the collection (expensive). Only the expensive choice is safe. Again, you choose the strategy that makes most sense, the expensive choice is not forced on you.

like image 40
Hans Passant Avatar answered Sep 27 '22 23:09

Hans Passant