gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:29:17 29 4
gpt4 key购买 nike

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com