Dart的”多線程“
眾所周知,Dart是一門單線程的語言,我們可以將一些需要等待的任務(wù)放到異步操作中,但是異步任務(wù)必須等到線程空閑時才會去執(zhí)行,這是無法滿足我們某些場景的需求的。那Dart就沒有辦法實現(xiàn)類似子線程的功能嗎?而實際,Dart其實是有辦法實現(xiàn)類似多線程的功能的。
Isolate
Isolate調(diào)用
Isolate是一個非常底層的api,我們可以通過Isolate.spawn()方法進行調(diào)用。
void isolateTest() async {
print("外部代碼 1");
Isolate.spawn(isoFunc0, "msg");
print("外部代碼 2");
}
void isoFunc0(String message) {
// 模擬耗時操作
sleep(Duration(seconds: 2));
print("message is $message");
}
執(zhí)行結(jié)果為
flutter: 外部代碼 1
flutter: 外部代碼 2
flutter: message is msg
Isolate與異步操作的區(qū)別
我們知道異步操作并沒有開辟一條子線程,而是在線程空閑時去執(zhí)行異步操作。而Isolate不同,我們可以通過下面代碼看到區(qū)別。
void isolateTest() async {
print("外部代碼 1");
Isolate.spawn(isoFunc0, "msg");
sleep(Duration(seconds: 3));
print("外部代碼 2");
}
void isoFunc0(String message) {
print("message is $message");
}
執(zhí)行結(jié)果為:
flutter: 外部代碼 1
flutter: message is msg
flutter: 外部代碼 2
可以看到,盡管主線程中有任務(wù)執(zhí)行沒有空閑,但是Isolate.spawn的操作仍然執(zhí)行了,這是異步操作所不具備的。
Isolate不是嚴格意義上的多線程
實際上,Isolate更像是進程而不是線程,因為他擁有獨立的內(nèi)存空間,并且他與子線程之間的通信需要借助到端口(Port)概念的api,這些特性讓它看起來更像是進程。
我們通過代碼驗證一下:
String _data = "0";
void isolateTest() async {
print("外部代碼 1");
Isolate.spawn(isoFunc0, "msg");
sleep(Duration(seconds: 3));
print("data is $_data");
print("外部代碼 2");
}
void isoFunc0(String message) {
_data = message;
print("message is $_data");
}
結(jié)果為:
flutter: 外部代碼 1
flutter: message is msg
flutter: data is 0
flutter: 外部代碼 2
可以看到,盡管Isolate中修改了_data的值,但是外部的_data的值并沒有隨之改變,顯然,這個結(jié)果明顯不符合多線程的特性。
ReceivePort
如果我們需要將Isolate的結(jié)果返回,我們需要使用端口ReceivePort來進行傳遞。我們將ReceivePort作為參數(shù)傳遞給Isolate,Isolate執(zhí)行完成后通過Port的send方法將結(jié)果傳遞出來,外部通過listen得到結(jié)果。
void isolateTest() async {
print("外部代碼 1");
ReceivePort port = ReceivePort();
Isolate iso = await Isolate.spawn(isoFunc, port.sendPort);
port.listen((message) {
_data = message;
print("data is $_data");
port.close();
iso.kill();
});
print("外部代碼 2");
}
void isoFunc(SendPort port) {
sleep(Duration(seconds: 2));
port.send("msg");
}
執(zhí)行結(jié)果為:
flutter: 外部代碼 1
flutter: 外部代碼 2
flutter: data is msg
port.listen到結(jié)果后,我們要將端口關(guān)閉,殺死Isolate。
compute
除了Isolate,Dart還給我們提供compute接口。
查看compute定義:
final _ComputeImpl compute = _isolates.compute;
可以猜測compute是對Isolates的封裝,繼續(xù)點進去:
Future<R> compute<Q, R>(isolates.ComputeCallback<Q, R> callback, Q message, { String debugLabel }) async {
debugLabel ??= kReleaseMode ? 'compute' : callback.toString();
final Flow flow = Flow.begin();
Timeline.startSync('$debugLabel: start', flow: flow);
final ReceivePort resultPort = ReceivePort();
final ReceivePort errorPort = ReceivePort();
Timeline.finishSync();
final Isolate isolate = await Isolate.spawn<_IsolateConfiguration<Q, FutureOr<R>>>(
_spawn,
... ...
可以確定,compute是對Isolate的封裝。
compute的調(diào)用
compute的使用要比Isolate方便很多
void computeTest() async {
print("外部代碼 1");
compute(computeFunc, "msg").then((value) => print("value = $value"));
print("外部代碼 2");
}
String computeFunc(String message) {
print("computeFunc ${message}");
return message + "compute";
}
執(zhí)行結(jié)果為:
flutter: 外部代碼 1
flutter: 外部代碼 2
flutter: computeFunc msg
flutter: value = msgcompute
compute顯然比Isolate更加方便簡潔。
總結(jié)
盡管Isolate和compute為我們提供了類似多線程的功能,但實際上它更像是進程不是線程,頻繁使用明顯會消耗內(nèi)存,所以我們一般只用來處理復雜耗時的計算,而像網(wǎng)絡(luò)請求和文件讀寫,我們通過異步操作就可以解決我們的需求了。