Race condition in JavaScript with compound assignment

后端 未结 2 990
礼貌的吻别
礼貌的吻别 2021-02-20 13:38

I\'m not talking about complex race conditions involving the network or events. Rather, I seem to have found out that the += operator is not atomic in V8 (Chrome 58

2条回答
  •  礼貌的吻别
    2021-02-20 13:59

    Indeed, after replacing the acc += await n(c) line with:

    const ret = await n(c); acc += ret;
    

    the race condition was avoided.

    My guess is V8 didn't optimize acc += await n(c) to an ADD of the n() result over the memory location containing acc, but rather expanded it to acc = acc + await n(c);, and the initial value of acc when nForever(5.3) was first called, was 0.

    This is counter-intuitive to me, though not sure the V8 developers would consider it a bug.

提交回复
热议问题