是std :: regex线程安全吗? [英] Is std::regex thread safe?

查看:448
本文介绍了是std :: regex线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关于是一个静态boost :: wregex实例线程安全?,但是对于标准版本。我可以从具有相同regex对象的多个线程调用regex_search吗?

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?

推荐答案

声明 std :: regex 在每个方面都是线程安全的是一个漂亮的大胆的语句。

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.

但是,看一下 std :: regex_search 显示它需要 basic_regex object作为const参数。这意味着它受到标准库的保证,保证const修饰符表示thread-

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.

在标准版中:


[17.6.5.9/1]
本节指定实现应满足以防止数据竞争(1.10)的要求。除非另有规定,每个标准库函数都应满足每个要求。

[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]
一个C ++标准库函数不应直接或间接修改除当前线程以外的线程可访问的对象(1.10),除非对象通过函数的非const 参数直接或间接访问,包括 this

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

因此,除了使用标准库的实现中出现错误,相对于传入的 regex 对象,对 std :: regex_search 的调用是线程安全的。

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.

其他想法

std :: regex_search 是关于其 regex 参数的重入并不意味着你完全不在水。执行在线程安全调用的同时以非线程安全方式修改 regex 的操作,例如 std :: regex_search 仍然是未定义的行为。 basic_regex 作业运算子 std :: swap basic_regex 他们操作。知道这一点,你可能会更好地制作 regex 对象的副本,这应该以最低的性能成本,每个线程使用/修改其休闲。

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.

这篇关于是std :: regex线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆