std string与线程安全,是std :: regex线程安全吗?

C++11标准并未明确保证正则表达式库的线程安全,但根据标准规定,对于const参数的函数,如std::regex_search,其调用在传递的正则对象为const时是线程安全的。然而,需要注意的是,修改正则表达式的操作(如赋值、swap或imbue)可能不是线程安全的。因此,为了确保安全,建议每个线程使用正则表达式的副本。
摘要由CSDN通过智能技术生成

Related to Is a static boost::wregex instance thread-safe? but for the standarized version. Can I call regex_search from several threads with the same regex object?

解决方案

Claiming that std::regex is thread-safe in every respect is a pretty bold statement. The C++11 standard does not make such guarantees for the regex library.

However, looking at the prototype of std::regex_search shows that it it takes the basic_regex object as a const argument. This means that it is protected by the standard library's guarantee that the const modifier implies thread-safety of the function with respect to that argument.

In standardese, that is:

[17.6.5.9/1]

This section specifies requirements that implementations shall meet to prevent data races (1.10). Every standard library function shall meet each requirement unless otherwise specified. Implementations may prevent data races in cases other than those specified below.

[17.6.5.9/3]

A C++ standard library function shall not directly or indirectly modify objects (1.10) accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function’s non-const arguments, including this.

So, barring a bug in the implementation of the standard library that you use, it appears that calls to std::regex_search are thread-safe with respect to the regex object that is passed in.

Other thoughts:

Just because std::regex_search is re-entrant with respect to its regex argument does not mean that you are completely out of the water. Performing an operation that modifies a regex in a non-thread-safe manner at the same time as a thread-safe call such as std::regex_search is still undefined behaviour. basic_regex's assignment operator, std::swap, and basic_regex::imbue come to mind as non-thread-safe functions with respect to the basic_regex they operate on. Knowing this, it might be better for you to make a copy of the regex object, which should come at a minimal performance cost, for each thread to use/modify at its leisure.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值