5

Is it safe to declare a static/global variable with a fixed boost::wregex and then use it from multiple threads without worrying about the regex's internal state (if Boost has been compiled with BOOST_HAS_THREADS)?

e.g.

boost::wregex g_regex( L"common|test" );

then have multiple threads calling:

if ( boost::regex_search( test_str, g_regex ) )
...
snowdude
  • 3,854
  • 1
  • 18
  • 27
  • 1
    Read-only access to *any* variable is *always* safe in concurrent code, problems only begin to arise when you introduce write access from any of the concurrent contexts. In regex' case, I think all `regex_xxx` functions take the regex argument by const-reference aka don't modify it, and the only way the regex could modify itself from within `const` functions would be with `mutable` members, which I think isn't the case here. – Xeo Sep 04 '12 at 12:02
  • Great point, I hadn't noticed the const-ness of the regex argument. I assume that the regex implementation must be using stack variables to manage state. – snowdude Sep 04 '12 at 12:04

1 Answers1

4

http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/background_information/thread_safety.html

Class basic_regex and its typedefs regex and wregex are thread safe, in that compiled regular expressions can safely be shared between threads. The matching algorithms regex_match, regex_search, and regex_replace are all re-entrant and thread safe. Class match_results is now thread safe, in that the results of a match can be safely copied from one thread to another (for example one thread may find matches and push match_results instances onto a queue, while another thread pops them off the other end), otherwise use a separate instance of match_results per thread.

ForEveR
  • 55,233
  • 2
  • 119
  • 133