c++ - std::regex 线程安全吗?

标签 c++ regex thread-safety std

Is a static boost::wregex instance thread-safe?相关但对于标准化版本。我可以从具有相同 regex 对象的多个线程调用 regex_search 吗?

最佳答案

声称 std::regex在各个方面都是线程安全的是一个非常大胆的声明。 C++11 标准不对正则表达式库做出这样的保证。

但是,查看 std::regex_search 的原型(prototype)显示它将 basic_regex 对象作为 const 参数。这意味着它受到标准库的保护,保证 const 修饰符 implies thread-safety关于该参数的函数。

在标准语中,即:

[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.

因此,除非您使用的标准库的实现中存在错误,否则似乎对 std::regex_search 的调用相对于 regex 是线程安全的> 传入的对象。


其他想法:

仅仅因为 std::regex_search 相对于它的 regex 参数是可重入的,并不意味着你完全脱离了困境。在执行线程安全调用(例如 std::regex_search)的同时以非线程安全方式执行修改 regex 的操作仍然是未定义的行为。 basic_regexassignment operator , std::swap , 和 basic_regex::imbue关于它们操作的 basic_regex ,想到的是非线程安全函数。了解这一点后,您最好制作一个 regex 对象的拷贝,这应该以最小的性能成本提供,供每个线程在闲暇时使用/修改。

关于c++ - std::regex 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752910/

相关文章:

C++ : Implicit type conversion

javascript - try catch 星号 **(str)** 之间的封闭字符串

python - 如何避免在正则表达式中分组

java - Java中的 "this"如何转义构造函数?

c++ - 虚幻气体 : Print out the current value of an attribute to UI when it changes

c++ - 如何将 C++ 文件编译为 WebAssembly?

c# - 并行操作的线程安全

java - 最少阻塞 java 缓存

c++ - 在计算实验期间将结果写入文件的有效方法

regex - 如何在 VBA 字符串中查找字母和数字的组合?