Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrently using std::regex, defined behaviour?

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!

like image 677
Thomas Russell Avatar asked Jul 07 '13 19:07

Thomas Russell


1 Answers

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.

like image 112
ronag Avatar answered Nov 05 '22 12:11

ronag