Will Dart execute isolates in parallel in a multi-core environment?

后端 未结 3 462
终归单人心
终归单人心 2021-02-01 06:18

Question

Will isolates in Dart run in parallel utilizing all available cores on a multiple core environment, or will it multiplex on a single core?

Background

3条回答
  •  别那么骄傲
    2021-02-01 06:57

    Warning: the code below is out of date and does not work with Dart 1.0.

    Short answer

    Maybe.

    Long Answer

    The dart:isolate library guide states: "Isolates might run in a separate process or thread, depending on the implementation. For web applications, isolates can be compiled to Web workers, if they are available." (my emphasis)

    Running this code and observing your CPU load will tell you if your implementation does this or not.

    #import('dart:isolate');
    main() {
      for (var tmp = 0; tmp < 5; ++tmp) {
        SendPort sendPort = spawnFunction(runInIsolate);
        sendPort.call(tmp).then((reply) {
          print(reply);
        });
      }
    }
    
    runInIsolate() {
      port.receive((msg, SendPort reply) {
        var k = 0;
        var max = (5 - msg) * 100000000; 
        for (var i = 0; i < max; ++i) {
            i = ++i - 1;
            k = i;
        }
        reply.send("I received: $msg and calculated $k");
      });
    }
    

    The standalone dartvm will run isolates in parallel, utilizing all available cores. Browser implementations of Dart will likely vary depending on whether Web Workers are implemented or not.

提交回复
热议问题