箭作为工作者孤立 [英] Dart Isolates As Workers

查看:144
本文介绍了箭作为工作者孤立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已编辑以使问题更清晰。

我正在Dart中使用Isolates我可以找到的主要和隔离线程之间的通信的唯一方法是发送 call&然后从主线程。但是这是一个很好的方法,主线程将一些数据传递给隔离。

I am trying to work with Isolates (or Web Workers) in Dart. The only ways I can find to communicate between the main and isolate threads are send and call & then from the main thread. But that's a nice way for the main thread to pass some data to the isolate.

如果我想要隔离是生成信息的人呢?像一个游戏引擎,一个工人的所有物理,然后发送更新的世界信息到主线程?在JavaScript中,您可以随时发送数据。 Dart中有有效的方法吗?或者我还需要等待主线程调用我,然后将其传递给它吗?

What's if I want the isolate to be the one who generates information? Like a game engine that does all the physics in a worker and then sends an updated world information to the main thread? In JavaScript you can send data at any time. Is there an efficient way in Dart? Or do I still have to wait for the main thread to call me and then pass it to it?

我不知道,是否呼叫&

P.S. I wonder, does call & then block the thread until reply is done or not?

推荐答案

警告:此代码仅适用于非常老版本的Dart。

正如你提到要向孤立者发布消息一样,你需要在sendport上有一个句柄。

As you mention to post messages to a isolate you need to have a handle on it's sendport.

#import('dart:isolate');

main() {
  SendPort sendPort = spawnFunction(doWork);
  sendPort.call("hey 1").then((String res) => print("result was: [$res]"));
  sendPort.call("hey 2").then((String res) => print("result was: [$res]"));
}

doWork() {
  port.receive((msg, reply) {
    msg = "msg $msg";
    reply.send(msg);
  });
}

然而,由于Dart主线程本身是一个隔离,你可以发送数据到它通过使用全局端口函数:

however since the Dart main thread is itself an isolate you can send data to it by using the global port function:

#import('dart:isolate');
#import('dart:io');

main() {
   port.receive((data, reply) {
       // in here you can access objects created in the main thread
       print("handle [${data['text']}] for index ${data['index']}");
   });

   SendPort workPort = spawnFunction(doWork);
   workPort.send("msg", port.toSendPort());
}

doWork() {
   port.receive((msg, reply) {
      int i = 0;
      new Timer.repeating(1000, (Timer timer) {
         i++;
         var data = {
            "text": "$msg $i",
            "index": i
         };
         print("sending $data");
         reply.send(data);
      });
   });
}

请注意,有什么限制可以在隔离和也目前隔离在JS和VM上的行为不同。 此处中详细介绍了当前的限制。

Note there are certain limits about what can be send back and forth between isolates and also currently isolates act differently in JS and on the VM. The current limitations are well described here.

这篇关于箭作为工作者孤立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆