Dart程式設計 - 併發



併發是指同時執行多個指令序列。它涉及同時執行多個任務。

Dart使用Isolate作為並行工作的工具。dart:isolate包是Dart的解決方案,它可以處理單執行緒Dart程式碼,並允許應用程式更好地利用可用的硬體。

顧名思義,Isolate是執行程式碼的隔離單元。它們之間傳遞資料的唯一方式是透過傳遞訊息,就像在客戶端和伺服器之間傳遞訊息一樣。Isolate幫助程式開箱即用地利用多核微處理器。

示例

讓我們來看一個例子來更好地理解這個概念。

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方法可以方便地與其餘程式碼並行執行函式foospawn函式接受兩個引數:

  • 要生成的函式,以及
  • 將傳遞給生成的函式的物件。

如果沒有物件要傳遞給生成的函式,可以傳遞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#程式碼啟動新執行緒一樣,從執行程式碼中生成新的Isolate

Isolate與執行緒的不同之處在於,Isolate擁有自己的記憶體。無法在Isolate之間共享變數——Isolate之間通訊的唯一方式是透過訊息傳遞。

注意 - 不同的硬體和作業系統配置將產生不同的輸出。

Isolate與Future

非同步執行復雜的計算工作對於確保應用程式的響應性非常重要。Dart Future是一種在非同步任務完成後檢索其值的機制,而Dart Isolate是一種在實踐中抽象並行性和實現它的高階工具。

廣告