为什么C ++ STL不提供一组线程安全的容器? [英] Why does the C++ STL not provide a set of thread-safe containers?

查看:774
本文介绍了为什么C ++ STL不提供一组线程安全的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

关于STL线程安全和STL调试的问题

我目前正在从事一个使用C ++开发的项目。最近我们正在考虑用一些STL等同替换一些自定义的线程安全容器,以获得一些效率。

I'm currently being engaged in a project which is developed using C++. Recently we are considering replacing some self-defined thread-safe containers with some STL equivalents to gain some efficiency.

但是,在寻找一段时间后,我发现没有一个线程安全的容器提供在STL中,这意味着很多。有什么原因吗?

However, after looking for a while, I found that there is no a thread-safe container provided in STL at all, which surprises quite a lot. Is there any reason?

推荐答案

标准库容器确实提供了一些基本的线程安全性能是设计者更重要的设计目标

Standard Library containers do provide some basic thread safety, Performance was a more important design goal for designers of the Standard Library containers than safety.

所有标准库容器都保证:

同一容器的多个并发读取是安全的,但

如果有至少一个写线程,那么没有线程安全性不得有任何其他作者或读者。

All Standard Library containers guarantee:
Multiple concurrent reads from the same container are safe but
If there is atleast one writer thread, then there is no thread safety & there shall not be any other writer or reader.

标准库容器主要设计用于在单线程环境中高效工作,并且只提供基本线程安全性是一种确保不需要并发访问的容器的完整性能的方法。

The Standard Library containers were primarily designed for working efficiently in Single threaded environments and providing only basic thread safety is a way to ensure full performance for containers that do not need concurrent access.

基本线程安全性需要用户需要某种同步方法,以避免使用互斥体或锁定的竞争条件。锁定或其他形式的同步通常是昂贵的因此在不需要时需要避免。

The basic thread safety needs that users need some sort of synchronization methods to avoid race conditions through use of using mutexes, or locks.Locking or other forms of synchronization are typically expensive and hence need to be avoided when not necessary.

此外,给定标准库容器暴露的接口,容器的客户端或用户容易提供

Also, given the interfaces exposed by the Standard Library containers, It is easy for the client or user of the container to provide the necessary locking by wrapping the underlying container operations with a lock acquisition and release if intended use is for multi-threaded environments.

17.6.3.10共享对象和库[res.on.objects] / strong>

17.6.3.10 Shared objects and the library [res.on.objects]


如果调用来自不同线程的标准库函数可能引入数据竞争,则程序的行为是未定义的。这可能发生的条件在17.6.4.8中规定。 [注意:修改线程之间共享的标准库类型的对象可能会面临未定义的行为,除非该类型的对象被明确指定为没有数据族的可共享或用户提供锁定机制。 -end note]

The behavior of a program is undefined if calls to standard library functions from different threads may introduce a data race. The conditions under which this may occur are specified in 17.6.4.8. [ Note: Modifying an object of a standard library type that is shared between threads risks undefined behavior unless objects of that type are explicitly specified as being sharable without data races or the user supplies a locking mechanism. —end note ]

这篇关于为什么C ++ STL不提供一组线程安全的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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