-1

According to my understanding, in JS there are not race conditions for synchronous code. That is, during the execution of a function variables should only be accessed by 1 executing thread.

However, I have run across this: enter image description here

In this image you can observe how the predicate of the if statement in line 186 evaluates to true. The code inside the if statement contains only a return statement. Hence, there is no way the thread could have escaped the if statement.

Some context into what sort of functions are calling into this:

This is a service worker MV3 extension.

A number of function stacks are awaiting for the closePromise. Once the close promise resolves, my premise is that the first "thread" to call __innitialize will pass the if statements into the executing thread. When the next "thread" calls __initialize, then the first one would have changed the state to INITIALIZING, thus he would enter the first if statement, and await for the initPromise.

I may not provide anymore than this snippet due to company policy.

LetsDoThis
  • 95
  • 6
  • FYI, I resolved the issue by changing the order of the if statements. Now state === INITIALIZING is done the very last, and variable assignment is done right away. I also added a bit of extra entropy by sleeping randomly between 0-15ms (initialization is not done too often so it's ok). – LetsDoThis May 20 '22 at 04:44
  • "*there are not race conditions for synchronous code*" - yes, but [there are exceptions](https://stackoverflow.com/a/2734311/1048572). None of which appear in your case though – Bergi Jun 20 '22 at 00:14

1 Answers1

2

(V8 developer here.) I agree that concurrent modification can't happen in JavaScript. The other obvious explanation (that the JS engine incorrectly checked the condition) would be a severe (and pretty obvious!) bug.

But without further information or a repro, it's hard to say anything for sure. For instance, if this is an embedder-provided object and .__state is an intercepted property, then anything could happen, and it's entirely outside of V8's control. You also mention "sleeping" in the comment: sleeping (and awaiting) are interruptions of synchronous control flow, so if you have such things in your code, that could also explain why things appear to "magically" change after such a point.

jmrk
  • 34,271
  • 7
  • 59
  • 74