Is JavaScript guaranteed to be single-threaded?

后端 未结 12 1668
遇见更好的自我
遇见更好的自我 2020-11-21 06:38

JavaScript is known to be single-threaded in all modern browser implementations, but is that specified in any standard or is it just by tradition? Is it totally safe to assu

12条回答
  •  伪装坚强ぢ
    2020-11-21 06:51

    No.

    I'm going against the crowd here, but bear with me. A single JS script is intended to be effectively single threaded, but this doesn't mean that it can't be interpreted differently.

    Let's say you have the following code...

    var list = [];
    for (var i = 0; i < 10000; i++) {
      list[i] = i * i;
    }
    

    This is written with the expectation that by the end of the loop, the list must have 10000 entries which are the index squared, but the VM could notice that each iteration of the loop does not affect the other, and reinterpret using two threads.

    First thread

    for (var i = 0; i < 5000; i++) {
      list[i] = i * i;
    }
    

    Second thread

    for (var i = 5000; i < 10000; i++) {
      list[i] = i * i;
    }
    

    I'm simplifying here, because JS arrays are more complicated then dumb chunks of memory, but if these two scripts are able to add entries to the array in a thread-safe way, then by the time both are done executing it'll have the same result as the single-threaded version.

    While I'm not aware of any VM detecting parallelizable code like this, it seems likely that it could come into existence in the future for JIT VMs, since it could offer more speed in some situations.

    Taking this concept further, it's possible that code could be annotated to let the VM know what to convert to multi-threaded code.

    // like "use strict" this enables certain features on compatible VMs.
    "use parallel";
    
    var list = [];
    
    // This string, which has no effect on incompatible VMs, enables threading on
    // this loop.
    "parallel for";
    for (var i = 0; i < 10000; i++) {
      list[i] = i * i;
    }
    

    Since Web Workers are coming to Javascript, it's unlikely that this... uglier system will ever come into existence, but I think it's safe to say Javascript is single-threaded by tradition.

提交回复
热议问题