简体   繁体   English

std :: map和std :: set线程安全吗?

[英]Are std::map and std::set thread-safe?

I have a question: Are std::map and std::set thread-safe? 我有一个问题:std :: map和std :: set线程安全吗? 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. C ++标准对此一无所获。1您将不得不查看所使用标准库的特定实现的文档。 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. 1. C11之前的版本。

No, they are not defined to be thread safe. 不,它们的定义不是线程安全的。 You have to add synchronization mechanisms on top of standard library containers. 您必须在标准库容器的顶部添加同步机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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