简体   繁体   English

请解释区域设置中对互斥锁的需求

[英]Explain the Need for Mutexes in Locales, Please

Reading the question Why doesn't C++ STL support atoi(const string& ) like functions? 阅读问题为什么C ++ STL不支持atoi(con​​st string&)函数? , I encountered a comment which warned that GCC (at least) has a bug that can slow down multi-threaded applications which use ostringstream frequently. ,我遇到一条评论警告GCC(至少)有一个错误 ,可以减慢频繁使用ostringstream的多线程应用程序。 This is apparently due to a mutex 'needed' by the C++ locale machinery. 这显然是由于C ++语言环境机制需要的互斥量。

Given my recent interest in globalization practices, I wonder if anyone can explain to me why a locale object would need a mutex? 鉴于我最近对全球化实践感兴趣 ,我想知道是否有人可以向我解释为什么语言环境对象需要互斥锁? What is it that can be changed in a locale that needs a mutex? 在需要互斥锁的区域设置中可以更改的是什么? Shouldn't it be a read-only facility? 它不应该是一个只读设施吗?

It's really an implementation issue, but std::locale has a static function that retrieves and set the 'global' locale. 这确实是一个实现问题,但是std::locale有一个静态函数,可以检索和设置'全局'语言环境。 The global locale is defined to be used in several areas of the standard library which implies that there must be a global locale somewhere. 全局语言环境定义为在标准库的几个区域中使用,这意味着某处必须存在全局语言环境。

In implementations that support threads it is very likely that this global locale needs to be protected via some sort of locking mechanism to prevent simultaneous access between threads from causing undesired behaviour. 在支持线程的实现中,很可能需要通过某种锁定机制来保护此全局区域设置,以防止线程之间的同时访问导致不期望的行为。

As the current standard does not explicitly deal with threading at all, it's a set implementation choices as to how (or if) this locking mechanism is implemented and whether other shared data and locks are required. 由于当前标准根本没有明确地处理线程,因此它是关于如何(或者如果)实现此锁定机制以及是否需要其他共享数据和锁的集合实现选择。

The answer is probably lazy initialization. 答案可能是懒惰的初始化。 There's a lot of data behind the locale system, and it's pretty easy to make the mistake of coding the sequence: 语言环境系统背后有很多数据,很容易犯错误编码序列:

  1. take lock 拿锁
  2. check for initialization 检查初始化
  3. read data if needed 如果需要,读取数据
  4. release lock 解锁

and there you are. 那就是你。

Some of us don't trust the entire iostream mechanism as far as we can throw it from a threading performance standpoint. 我们中的一些人不相信整个iostream机制,只要我们可以从线程性能的角度抛出它。 Since, oh, 1987, it has been full of unwanted locks with no way to declare that a single stream will be only used in a single thread. 自1987年以来,它已经充满了不必要的锁,无法声明单个流只能在单个线程中使用。

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

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