Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are STL Map or HashMaps thread safe?

Tags:

c++

stl

Can I use a map or hashmap in a multithreaded program without needing a lock? i.e. are they thread safe?

I'm wanting to potentially add and delete from the map at the same time.

There seems to be a lot of conflicting information out there.

By the way, I'm using the STL library that comes with GCC under Ubuntu 10.04

EDIT: Just like the rest of the internet, I seem to be getting conflicting answers?

like image 241
hookenz Avatar asked Aug 09 '10 05:08

hookenz


1 Answers

You can safely perform simultaneous read operations, i.e. call const member functions. But you can't do any simultaneous operations if one of then involves writing, i.e. call of non-const member functions should be unique for the container and can't be mixed with any other calls.

i.e. you can't change the container from multiple threads. So you need to use lock/rw-lock to make the access safe.

like image 59
Artyom Avatar answered Oct 07 '22 04:10

Artyom