Search code examples
c++boostboost-spiritboost-spirit-qiboost-spirit-x3

Are boost spirit V2 Qi grammars thread safe?


While reading the boost spirit V2 docs, this SO-question and this top google spirit doc result for spirit classic/v1 I was not able to find any statement on the thread safety of boost spirit V2 grammars and rules. Some are claiming it's not like in classic anymore and a #define BOOST_SPIRIT_THREADSAFE wouldn't have any effect, but still if V2 doesn't make different from classic in regards to thread safety, the mention source isn't very clear about if it's speaking about distinct instances or shared instances.

So my primary question is:


1. Are distinct spirit V2 grammar objects thread safe?

And optional if one knows:

2. Are shared spirit V2 grammars objects thread safe?

3. Are distinct spirit V2 rule objects thread safe?

4. Are shared spirit V2 rule objects thread safe?

I also flagged it for spirit x3 since it's the same question there.


Solution

  • Indeed BOOST_SPIRIT_THREADSAFE doesn't apply to Qi in any way, it was for Classic.

    With that out of the way, the only thing that thread safety depends on is whether Boost is built with thread support. All indications I have found in half a decade are that no library explicitly supports building without thread support anymore. (What exactly does `threading=multi` do when compiling boost?).

    Non-terminals (grammars and rules) are thread safe unless you derive your own grammar that's not stateless and the parse operation is not const.

    In practice, prefer to write your parsers so they can be explicitly const-qualified:

    Parser const p;
    
    book ok = parse(f, l, p);
    

    X3 makes it easier to prove threadsafety because rules are usually const global statics (or even constexpr) and inherently stateless.