1

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.

Superlokkus
  • 4,731
  • 1
  • 25
  • 57

1 Answers1

2

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.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • I am not sure when a grammar is stateless and when not. I assume at least when I do semantic actions which perform write side effects on its members or outside. But I'm not sure if stateless still applies when just assigning some rules in the ctor and using the struct mapping mechanism other wise via boost fusion and parser attributes. If you would have a statement on that too, your answer would be perfect, besides from already helping/calming down me a lot. Thank you! – Superlokkus Oct 10 '18 at 12:28
  • 1
    If the rules are bitwise const that's always safe. It they're logically const that's usually safe - at least disciplined libraries tend to guard that (https://stackoverflow.com/questions/14127379/does-const-mean-thread-safe-in-c11). They're indeed stateless unless you add your own state. Logically, you just make sure you can use a `const` instance of your parser. Unless you did const-cast like hacks or are storing references to mutable state outside the parser it should be threadsafe. If not, it will be as thread-safe as that mutable state is. – sehe Oct 10 '18 at 14:50