【问题标题】:Is std::to_string thread safe?std::to_string 线程安全吗?
【发布时间】:2017-12-23 20:09:19
【问题描述】:

我希望使用std::to_string 将整数类型转换为字符串,但我看到了这段:

std::to_string 依赖于std::locale 进行格式化,并且 因此从多个线程并发调用std::to_string 可能 导致调用的部分序列化。

但是我找不到关于这个主题的任何其他内容,Google 没有提出任何建议,MSDN 也是如此。如果重要的话,我正在使用 Visual Studio 2013。

这个线程安全吗?如果是这样,怎么做?

【问题讨论】:

  • 没有任何关于引号的内容表明它不是线程安全的。只是多个调用可能不会同时运行。这是性能问题,而不是安全问题。
  • @Nathan 请求问题是 std::locale 线程安全吗?
  • @NeilButterworth 部分不是。例如,setlocale 不是线程安全的,因此std::to_string 可能会使用互斥锁来确保多个调用在调用时不会竞争。
  • 对于std::locale类本身:它是不可变的,所以不存在读/写竞争的可能性

标签: c++ multithreading c++11 language-lawyer


【解决方案1】:

std::to_string 的行为就好像它调用了sprintf ([string.conversions]/7),而sprintf 的行为取决于全局语言环境,可以通过setlocale(或std::locale::global,在内部致电setlocale)。

[clocale.syn]/2 中的措辞似乎暗示std::to_string 是线程安全的,因为它不允许setlocale 引入与std::to_string 或sprintf 的数据竞争。

【讨论】:

  • 感谢您的详细解答
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 2018-03-31
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多