简体   繁体   中英

Are std::map and std::set thread-safe?

I have a question: Are std::map and std::set thread-safe? I use this collections on my multithread applications and sometimes map and set works worng.

Thanks!

upd. My code:

std::map<int, unsigned long> ClientTable;

int sendulong(int socket, char * data) //<--- Many threads uses this function
{
  write(socket, ClientTable[socket]); //<--- ClientTable[[socket] <-- using of map
}

How can i fix this code for thread safety? Thanks!

It depends on what you want to do. If all you're doing is reading from them, then yes. If you also write to them and a separate thread attempts to do anything else, or has living iterators, it won't work as expected.

The C++ standard says nothing about this.1 You will have to look at the documentation for the particular implementation of the standard library that you're using. But it's quite likely that it won't be thread-safe, so you will need to do synchronisation yourself.

(If you want to know how to do that, well, that's a different question topic...)


1. Pre-C11.

No, they are not defined to be thread safe. You have to add synchronization mechanisms on top of standard library containers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM