How to use HashMap in multi-theading application safely

Please post support and help requests here.
tiplip
Posts: 18
Joined: 13 Jan 2011, 09:21

How to use HashMap in multi-theading application safely

Postby tiplip » 11 Jul 2013, 08:54

I have a multi-threading application and each thread will possibly use insert/find/erase/access all items using Iterator, should I add mutex before each method to secure no race-condition?

alex
Posts: 1294
Joined: 11 Jul 2006, 16:27
Location: United_States

Re: How to use HashMap in multi-theading application safely

Postby alex » 14 Jul 2013, 20:32

yes

tiplip
Posts: 18
Joined: 13 Jan 2011, 09:21

Re: How to use HashMap in multi-theading application safely

Postby tiplip » 15 Jul 2013, 03:57

hi alex, let me give more information about my scenario as follows, maybe will have another solution? :)

I have a threaded application, each thread will probably insert specific item into map, or erase its inserted item from map, but for any other threads, they will just use find or traverse the whole map via iterator.

Again, each thread will only insert or erase one its specific item on map.

In such case, should I add lock before insert or erase to avoid race? how about traverse using iterator or find?


Actually, I posted the same question here as well http://stackoverflow.com/questions/17608882/how-to-use-stdmap-in-threaded-application-safely

alex
Posts: 1294
Joined: 11 Jul 2006, 16:27
Location: United_States

Re: How to use HashMap in multi-theading application safely

Postby alex » 15 Jul 2013, 23:28

HashTable documentation wrote:This class is NOT thread safe.

So, as I said, you should lock on everything (insert/erase/iterate). If you want to avoid locking on iteration, try having an immutable map with heap-preallocated space pointers as values and then new/destruct your data in-place, without ever touching the map itself. That way, you only have to lock on new/destruct. If I get your problem right, that is.


Return to “Support”

Who is online

Users browsing this forum: No registered users and 2 guests