Concurrently using std::regex, defined behaviour?

2020-07-02 11:21发布

Is it possible to use a std::regex object in multiple threads all using std::sregex_iterator, std::regex_match, etc.?

For instance, would the following produce logical behaviour:

bool SomeFunc( const std::string& szString1, const std::string& szString2 ) 
{
     static const std::regex regexTest( "=== ([\\w]+) ===", std::regex_constants::optimize );

     std::future<bool> f = std::async( []( std::string szString ) {
        return std::regex_match( szString, regexTest );  
     }, szString1 );

     bool b = std::regex_match( szString2, regexTest );

     return (b && f.get());
}

I can't find anything which states whether using a const std::regex concurrently results in undefined behaviour or not. As far as I can tell, no edits are being made to the regex object so no undefined behaviour should be induced by using it concurrently?

Thanks in advance!

1条回答
疯言疯语
2楼-- · 2020-07-02 11:45

Yes, a const std::regex is thread-safe. Actually any const method in the standard library is thread-safe, see:

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

查看更多
登录 后发表回答