10.Dart - isolates隔離

個人學習用
不嚴謹
學習的話請看別的博客

void main(){
  /**
   * 爲了解決多線程帶來的併發問題,Dart 使用 isolates 替代線程
   * 所有的 Dart 代碼均運行在一個 isolates 中。
   * 每一個 isolates 有它自己的堆內存以確保其狀態不被其它 isolates 訪問。
   */
}

互相發送消息

//dart是單線程模型的語言,但是開發中我們經常會進行耗時操作,比如網絡請求,這種請求會阻塞我們的代碼
//dart的併發機制 叫 isolate ,
//App的啓動入口main函數就是類似於Android主線程的主isolate
//和java的Thread不同,dart中的isolate是無法共享內存的

import 'dart:isolate';

int i;

void main() {

  i = 10;

  //1.創建一個消息接收器
  ReceivePort port = new ReceivePort();

  //2.創建isolate線程
  Isolate.spawn(isolateMain, port.sendPort);

  //3.用接收器receiveport接受其他isolate發來的消息
  port.listen((message) {
    //發過來的sendPort,則主isolate也可以向創建的isolate發送消息
    if (message is SendPort) {
      message.send("接受消息成功~");
    } else {
      print("接到子isolate消息:" + message);
    }
  });

}

//新的isolate
void isolateMain(SendPort port) {

  //isolate是內存隔離的,i的值實在主isolate定義的,所以這裏獲取爲null
  print(i); //null

  //1.創建一個消息接收器
  ReceivePort receivePort = new ReceivePort();
  port.send(receivePort.sendPort);
  //2.向主isolate發送消息
  port.send("我發送消息啦~~~");

  //3.接受數據的方法
  receivePort.listen((message) {
    print("接收到的isloate消息:" + message);
  });
}

##並行

import 'dart:isolate';

void main() {
  Isolate.spawn(iso1, "");
  Isolate.spawn(iso2, "");
  while (true) {}
}

void iso1(msg) {
  print("iso1 執行");
  Future.doWhile(() {
    print("1");
    return true;
  });
}

void iso2(msg) {
  print("iso2 執行");
  Future.doWhile(() {
    print("2");
    return true;
  });
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章