Dart中多核CPU的利用

2020-11-18  本文已影响0人  刘铁崧

Isolate

Dart是单线程的,这个线程有自己可以访问的内存空间以及需要运行的事件循环,这个空间可以称之为是一个isolate。
Flutter中有一个root isolate,负责运行flutter代码(UI渲染、用户交互等)

简单实用isolate

void main() {
  print("start");
  Isolate.spawn(addFunc, 3);
  print("end");
  // runApp(MyApp());}
void addFunc(int count){
  var total = 0;
  for (var i = 0; i < count; i++){
    total += 1;
  }
  print(total);
}
Debug service listening on ws://127.0.0.1:65051/xf8TMtGS2nk=/ws
Syncing files to device iPhone 12 Pro Max...
flutter: start
flutter: end
flutter: 3

isolate的反向向通信

Future<void> main() async {
  print("start");
  // 创建管道
  ReceivePort receivePort = ReceivePort();
  // 创建isolate
  Isolate isolate = await Isolate.spawn<SendPort>(testISO,receivePort.sendPort);
  // 监听管道
  receivePort.listen((message) {
    print(message);
    // 关掉管道与isolate
    receivePort.close();
    isolate.kill();
  });
  print("end");
  // runApp(MyApp());
}
void testISO(SendPort sendport){
  sendport.send("消息");
}
Debug service listening on ws://127.0.0.1:50021/2MBbGZk0pe0=/ws
Syncing files to device iPhone 12 Pro Max...
flutter: start
flutter: end
flutter: 消息

Flutter开发中如果想要创建,有更好的封装方法:compute
注:testISO必须是static或者顶层函数

class _ESTestState extends State<ESTest> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    testIsolate();
  }
  Future<void> testIsolate() async {
    print("start");
    var result = await compute(testISO,"hello");
    print(result);
    print("end");
  }
  @override
  Widget build(BuildContext context) {
    return RaisedButton();
  }
}
String testISO(String message){
  return message + "world";
}
上一篇下一篇

猜你喜欢

热点阅读