我有大约 10k 个需要按顺序计算的长时间运行的任务。为此,我决定使用 Isolates。问题是我应该每次为每个单独的任务创建生成隔离,还是应该只为所有任务的执行创建一个隔离。我不知道创建 Isolates 的成本是多少。
创建一个隔离并将其用于所有任务的源:
import 'dart:isolate';
class DataPacket {
SendPort port;
int result;
}
class SquareRootCalculator {
final ReceivePort _masterPort = new ReceivePort();
SendPort _workerPort;
SquareRootCalculator() {
Isolate.spawn(isolateFunction, _masterPort.sendPort).then((isolate) {
_masterPort.listen((data) {
if (_workerPort == null)
_workerPort = data.port;
else {
print(data.toString());
}
});
});
}
input(int n) {
_workerPort.send(n);
}
}
void isolateFunction(SendPort masterPort) {
ReceivePort _workerPort = new ReceivePort();
DataPacket packet = new DataPacket();
packet.port = _workerPort.sendPort;
packet.result = -1;
masterPort.send(packet);
_workerPort.listen((data) {
int out = calculate(data);
DataPacket packet = new DataPacket();
packet.port = _workerPort.sendPort;
packet.result = out;
masterPort.send(packet);
});
}
int calculate(int number) {
for (var i = 0; i < 1000000000; ++i) {} // long running task
return number * number;
}
我可以推送任务
SquareRootCalculator _calc = new SquareRootCalculator();
for(int i = 0; i < 100; ++i){
_calc.input(i); //task
sleep(const Duration(seconds:1));
}