unordered_map 线程安全

unordered_map thread safety(unordered_map 线程安全)

本文介绍了unordered_map 线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 boost:thread 库将单线程程序更改为多线程程序.该程序使用 unordered_map 作为 hasp_map 进行查找.我的问题是..

I am changing a single thread program into multi thread using boost:thread library. The program uses unordered_map as a hasp_map for lookups. My question is..

一次有很多线程在写,而在另一次有很多线程在读,但不是同时读和写,即要么所有线程都在读,要么都在写.那会是线程安全的吗?为此而设计的容器?如果是,它真的会并发并提高性能吗?我需要使用一些锁定机制吗?

At one time many threads will be writing, and at another many will be reading but not both reading and writing at the same time i.e. either all the threads will be reading or all will be writing. Will that be thread safe and the container designed for this? And if it will be, will it really be concurrent and improve performance? Do I need to use some locking mechanism?

我在某处读到 C++ 标准说行为将是未定义的,但仅此而已吗?

I read somewhere that the C++ Standard says the behavior will be undefined, but is that all?

更新:我也在考虑英特尔 concurrent_hash_map.这会是一个不错的选择吗?

UPDATE: I was also thinking about Intel concurrent_hash_map. Will that be a good option?

推荐答案

STL 容器的设计保证您能够:

STL containers are designed so that you are guaranteed to be able to have:

A.多线程同时读取

B.一个线程同时写入

多线程写入不是上述情况之一,是不允许的.因此,多线程写入会造成数据竞争,这是未定义的行为.

Having multiple threads writing is not one of the above conditions and is not allowed. Multiple threads writing will thus create a data race, which is undefined behavior.

您可以使用互斥锁来解决此问题.shared_mutex(与 shared_locks 结合)将特别有用,因为这种类型的互斥锁允许多个并发读取器.

You could use a mutex to fix this. A shared_mutex (combined with shared_locks) would be especially useful as that type of mutex allows multiple concurrent readers.

http://eel.is/c++draft/res.on.data.races#3 是标准的一部分,它保证了在不同线程上同时使用 const 函数的能力.http://eel.is/c++draft/container.requirements.dataraces 指定一些额外的非常量操作,它们在不同线程上是安全的.

http://eel.is/c++draft/res.on.data.races#3 is the part of the standard which guarantees the ability to concurrently use const functions on different threads. http://eel.is/c++draft/container.requirements.dataraces specifies some additional non-const operations which are safe on different threads.

这篇关于unordered_map 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:unordered_map 线程安全

基础教程推荐