13

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 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

19 Comments

Thank you, that's what I figured; I just wanted confirmation.
@ronag Could you explain in your answer why they chose for this specification? Also how is this achieved with a class which isn't part of the C++ standard library? I hope you will find the time to answer those questions! :)
@Tim "Also how is this achieved with a class which isn't part of the C++ standard library?" I don't understand your question...
@curiousguy Sorry I meant something else; the statement says that a const instance of any class called by a function from the C++ standard library is thread-safe, right? What if I want to make my own function thread-safe?
@Tim: The C++ standard does not specify how things should be implemented in the standard library, it's totally up to each standard library implementer. I think you are looking for another question. But yes there are several tools to achieve thread-safety, std::atomic, std::mutex, thread_local etc...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.