unordered_map线程安全 [英] unordered_map thread safety

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

问题描述

我使用升压改变一个单线程程序为多线程。该方案采用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. Multiple threads reading at the same time, or

乙。一个线程在同一时间写

B. One thread writing at the same time

具有多个线程写入不是上述条件之一,是不允许的。多线程编写从而将创建一个数据的比赛,这是不确定的行为。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆