Flutter 多线程实现

 

异步Isolate实现多线程

 

最近在看Flutter开发相关知识点,对照着Android原生,探究了下多线程实现方式。在Flutter中有 Isolate,隔离,它的实现原理并不是内存共享的,它更像是一个进程。

最简单的 compute

 

import 'dart:convert';

main(List<String> args) {
  String jsonString = '''{ "id":"1234", "name":"hahaha"}''';
  People people = parseJson(jsonString);
  print(people.name);
}

Student parseJson(String json) {
  Map<String, dynamic> map = jsonDecode(json);
  return People.fromJson(map);
}

class People{
  String id;
  String name;
  People({this.id, this.name});
  factory People.fromJson(Map parsedJson) {
    return People(id: parsedJson['id'], name: parsedJson['name']);
  }
}

我们需要把上面代码放入isolate中执行

isolate
Future<People> loadPeople(String json) {
  return compute(parseJson, json);
}

Student parseJson(String json) {
  Map<String, dynamic> map = jsonDecode(json);
  return People.fromJson(map);
}

compute是 Flutter 的 api ,帮我们封装了 isolate,使用十分简单,但是也有局限性, 它没有办法多次返回结果,也没有办法持续性的传值计算,
每次调用,相当于新建一个隔离,如果同时调用过多的话反而会多次开辟内存。在某些业务下,我们可以使用compute,
但是在另外一些业务下,我们只能使用dart提供的 isolate了。这个有点像AIDL和Messager的关系。
 
import 'dart:convert';
import 'dart:isolate';

main(List<String> args) async {
  await start();
}

Isolate isolate;

start() async {
  //创建接收端口,用来接收子线程消息
  ReceivePort receivePort = ReceivePort();

  //创建并发Isolate,并传入主线程发送端口
  isolate = await Isolate.spawn(entryPoint, receivePort.sendPort);
  //监听子线程消息
  receivePort.listen((data) {
    print('Data:$data');
  });
}

//并发Isolate
entryPoint(SendPort sendPort) {
  String jsonString = '''{ "id":"123", "name":"张三"}''';
  People people = parseJson(jsonString);
  sendPort.send(people);
}

Student parseJson(String json) {
  Map<String, dynamic> map = jsonDecode(json);
  return People.fromJson(map);
}

class people {
  String id;
  String name;
  People({this.id, this.name});
  factory People.fromJson(Map parsedJson) {
    return People(id: parsedJson['id'], name: parsedJson['name']);
  }
}


我们需要从主线程传参给子线程,或者像线程池一样可以管理这个isolate,那么我们就需要实现双向通信:
import 'dart:isolate';

main(List<String> args) async {
// 在主线程里面 await start(); await Future.delayed(Duration(seconds: 1), () { threadPort.send('主线程'); print('1'); }); await Future.delayed(Duration(seconds: 1), () { threadPort.send('我也来自主线程'); print('2'); }); await Future.delayed(Duration(seconds: 1), () { threadPort.send('end'); print('3'); }); } Isolate isolate; //子线程发送端口 SendPort threadPort; start() async {
// 在主线程 //创建主线程接收端口,用来接收子线程消息 ReceivePort receivePort = ReceivePort(); //创建并发Isolate,并传入主线程发送端口 isolate = await Isolate.spawn(entryPoint, receivePort.sendPort); //监听子线程消息 receivePort.listen((data) { print('主线程收到来自子线程的消息$data'); if (data is SendPort) { threadPort = data; } }); } //并发Isolate entryPoint(dynamic message) {
// 在子线程里面 //创建子线程接收端口,用来接收主线程消息 ReceivePort receivePort = ReceivePort(); SendPort sendPort; print('==entryPoint==$message'); if (message is SendPort) { sendPort = message; print('子线程开启'); sendPort.send(receivePort.sendPort); //监听子线程消息 receivePort.listen((data) { print('子线程收到来自主线程的消息$data'); assert(data is String); if (data == 'end') { isolate?.kill(); isolate = null; print('子线程结束'); return; } }); return; } }
双向通信比较复杂,所以我们需要封装下,通过 api 让外部调用:
import 'dart:async';
import 'dart:isolate';

main(List<String> args) async {
  var worker = Worker();
  worker.reuqest('发送消息1').then((data) {
    print('子线程处理后的消息:$data');
  });

  Future.delayed(Duration(seconds: 2), () {
    worker.reuqest('发送消息2').then((data) {
      print('子线程处理后的消息:$data');
    });
  });
}

class Worker {
  SendPort _sendPort;
  Isolate _isolate;
  final _isolateReady = Completer<void>();
  final Map<Capability, Completer> _completers = {};

  Worker() {
    init();
  }

  void dispose() {
    _isolate.kill();
  }

  Future reuqest(dynamic message) async {
    await _isolateReady.future;
    final completer = new Completer();
    final requestId = new Capability();
    _completers[requestId] = completer;
    _sendPort.send(new _Request(requestId, message));
    return completer.future;
  }

  Future<void> init() async {
  // 在主线程里面 final receivePort = ReceivePort(); final errorPort = ReceivePort(); errorPort.listen(print); receivePort.listen(_handleMessage); _isolate = await Isolate.spawn( _isolateEntry, receivePort.sendPort, onError: errorPort.sendPort, ); } void _handleMessage(message) { if (message is SendPort) { _sendPort = message; _isolateReady.complete(); return; } if (message is _Response) { final completer = _completers[message.requestId]; if (completer == null) { print("Invalid request ID received."); } else if (message.success) { completer.complete(message.message); } else { completer.completeError(message.message); } return; } throw UnimplementedError("Undefined behavior for message: $message"); } static void _isolateEntry(dynamic message) {
  // 在子线程里面 SendPort sendPort; final receivePort = ReceivePort(); receivePort.listen((dynamic message) async { if (message is _Request) { print('子线程收到:${message.message}'); sendPort.send(_Response.ok(message.requestId, '处理后的消息')); return; } }); if (message is SendPort) { sendPort = message; sendPort.send(receivePort.sendPort); return; } } } class _Request { /// The ID of the request so the response may be associated to the request's future completer. final Capability requestId; /// The actual message of the request. final dynamic message; const _Request(this.requestId, this.message); } class _Response { /// The ID of the request this response is meant to. final Capability requestId; /// Indicates if the request succeeded. final bool success; /// If [success] is true, holds the response message. /// Otherwise, holds the error that occured. final dynamic message; const _Response.ok(this.requestId, this.message) : success = true; const _Response.error(this.requestId, this.message) : success = false; }
posted @ 2023-07-26 16:56  玄武湖旁边的青蛙  阅读(380)  评论(0编辑  收藏  举报