Is it possible to use a
std::regex
object in multiple threads all usingstd::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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With