併發是同時執行多個指令序列。它涉及同時執行多個任務。
Dart使用Isolates
作為並行工作的工具。dart:isolate
包是Dart的解決方案,用於獲取單線程Dart代碼並允許應用程式更多地使用可用的硬體。
隔離(Isolates)顧名思義,是運行代碼的獨立單元。在它們之間發送數據的唯一方法是傳遞消息,就像在客戶端和服務器之間傳遞消息的方式一樣。隔離有助於程式利用多核微處理器開箱即用。
示例
下麵通過一個例子代碼來更好地理解這個概念。
import 'dart:isolate';
void foo(var message){
print('execution from foo ... the message is :${message}');
}
void main(){
Isolate.spawn(foo,'Hello!!');
Isolate.spawn(foo,'Greetings!!');
Isolate.spawn(foo,'Welcome!!');
print('execution from main1');
print('execution from main2');
print('execution from main3');
}
這裏,Isolate
類的spawn
方法用來與其餘代碼並行運行函數foo
。spawn
函數有兩個參數 -
- 催生功能
- 將傳遞給衍生函數的對象。
如果沒有對象傳遞給生成的函數,則可以傳遞NULL
值。
這兩個函數(foo
和main
)可能不一定每次都以相同的順序運行。無法保證foo
何時執行以及何時執行main()
。每次運行時輸出都不同。
輸出1
execution from main1
execution from main2
execution from main3
execution from foo ... the message is :Hello!!
輸出2
execution from main1
execution from main2
execution from main3
execution from foo ... the message is :Welcome!!
execution from foo ... the message is :Hello!!
execution from foo ... the message is :Greetings!!
從輸出中,可以得出結論,Dart代碼可以從運行代碼中產生新的隔離,就像Java或C#代碼可以啟動新線程一樣。
隔離與線程的不同之處在於隔離區有自己的記憶體。沒有辦法在隔離區之間共用變數 - 隔離區之間通信的唯一方法是通過消息傳遞。
注 - 對於不同的硬體和操作系統配置,上述輸出將有所不同。
隔離與Future
非同步執行複雜的計算工作對於確保應用程式的回應性非常重要。Dart Future是一種在完成後檢索非同步任務的值的機制,而Dart Isolates是一種抽象並行性並在實際的高級基礎上實現它的工具。
上一篇:
Dart非同步和非同步
下一篇:
Dart單元測試