3
头图

Preface

It seems that Dart has no traffic, even if it is on the homepage of Xiaobian Care, there are still very few people to see.

Forget it, continue to have a fever today, Dart 's write about how to use the 060de651ff269f language concurrent operation. Speaking of concurrent operations, Go should laugh. This is our housekeeping skill. The classmates who played PHP continued to take a look, indicating that we just can't speak.

Before the code demonstration, we first assume a scenario. Suppose I have some beautiful sisters who are going to travel, and they will send me photos when they travel. In this process, what the code needs to do:

  1. Receive request
  2. Arrange a travel plan and travel at the same time, there can be no priority
  3. They travel separately, you can send me photos
  4. Return result

During this process, what I care about is whether they can handle their own affairs well, because my sisters are too many, and if I are asked to help them, I can’t handle it to the point of exhaustion. I will do two things and arrange the travel plan. , And finally receive photos.

Let's demonstrate the code

import 'dart:io';
import 'dart:isolate';

main() async {
  print(DateTime.now().toString() + ' 开始');

  //这是一个接收端口,可以理解成我的手机
  ReceivePort receivePort = new ReceivePort();

  //安排三个妹妹出去旅行,让她们牢记我的手机号
  await Isolate.spawn(travelToBeijing, receivePort.sendPort);
  await Isolate.spawn(travelToShanghai, receivePort.sendPort);
  await Isolate.spawn(travelToGuangzhou, receivePort.sendPort);

  //我就在手机上,等待他们的消息
  receivePort.listen((message) {
    print(message);
  });

  print(DateTime.now().toString() + ' 结束');
}

void travelToBeijing(SendPort sendPort) {
  sleep(Duration(seconds: 3));
  sendPort.send(DateTime.now().toString() + ' 我是妹妹1,我在北京了');
}

void travelToShanghai(SendPort sendPort) {
  sleep(Duration(seconds: 3));
  sendPort.send(DateTime.now().toString() + ' 我是妹妹2,我在上海了');
}

void travelToGuangzhou(SendPort sendPort) {
  sleep(Duration(seconds: 3));
  sendPort.send(DateTime.now().toString() + ' 我是妹妹3,我在广州了');
}

What do you mean by writing so much above, let me explain the above code a little bit by myself.

Dart in concurrency, is used Isolate class.

Isolate translation of is the 160de651ff27e0 isolation area, which is an important class for Dart The principle of its concurrency is neither multi-process nor multi-thread. You said it is similar to the Go , but it is not like it.

It's really difficult to define it. I look forward to the preaching of students who have a deeper research on operating systems. Of course, this does not affect our use.

Isolate.spawn to define a concurrent task, receiving two parameters, the first is the processing function of the task, the second is the required parameters of the processing function

ReceivePort translates the receiving port, which can also be translated into the receiver, which is used to receive the messages returned by each task.

receivePort.listen used to monitor the return information of each task, and the code is simply printed

Execute it and get the printed result

2021-07-01 15:40:38.132122 开始
2021-07-01 15:40:38.295683 结束
2021-07-01 15:40:41.200316 我是妹妹1,我在北京了
2021-07-01 15:40:41.248851 我是妹妹2,我在上海了
2021-07-01 15:40:41.296737 我是妹妹3,我在广州了

Pay attention to the printed results, the sisters are very good, and basically replied to me at the same time. The total time is almost 3 seconds, you can add more tasks, it will be 3 seconds.

Encapsulate it again

Isolate , and students who use it don’t have to think about what the hell ReceivePort

import 'dart:io';
import 'dart:isolate';

class MultiTask {
  static void run(
      {List<TaskItem> taskList,
      Function taskFunc,
      Function onCompletedItem,
      Function onCompletedAll}) async {
    ReceivePort receivePort = new ReceivePort();

    Map<String, Isolate> mapParam = {};
    for (int i = 0; i < taskList.length; i++) {
      TaskItem taskItem = taskList[i];
      mapParam[taskItem.key] = await Isolate.spawn(
          taskFunc, TaskMessage(receivePort.sendPort, taskItem));
    }

    List<TaskRes> taskResList = [];
    receivePort.listen((message) async {
      TaskRes taskRes = message as TaskRes;
      if (null != onCompletedItem) await onCompletedItem(taskRes);
      taskResList.add(taskRes);
      mapParam[taskRes.key].kill();
      if (taskResList.length == taskList.length) {
        receivePort.close();
        if (null != onCompletedAll) await onCompletedAll(taskResList);
      }
    });
  }
}

class TaskMessage {
  SendPort sendPort;
  TaskItem taskItem;
  TaskMessage(this.sendPort, this.taskItem);
}

class TaskItem {
  String key;
  String param;

  TaskItem(this.key, this.param);
}

class TaskRes {
  String key;
  String res;

  TaskRes(this.key, this.res);
}

When using it, do it like this:

import 'dart:io';
import 'dart:isolate';
import 'MultiTask.dart';

main() async {
  List<TaskItem> taskList = [
    TaskItem('1', 'param1'),
    TaskItem('2', 'param2'),
    TaskItem('3', 'param1'),
    TaskItem('4', 'param2'),
    TaskItem('5', 'param1'),
    TaskItem('6', 'param2'),
    TaskItem('7', 'param1'),
    TaskItem('8', 'param2'),
    TaskItem('9', 'param1'),
    TaskItem('0', 'param2'),
  ];

  print(DateTime.now());

  MultiTask.run(
    taskList: taskList,
    taskFunc: taskFunc,
    onCompletedItem: (TaskRes taskRes) =>
        print(DateTime.now().toString() + '_' + taskRes.res),
    onCompletedAll: (List<TaskRes> taskResList) =>
        print(DateTime.now().toString() + '_onCompletedAll'),
  );
}

void taskFunc(TaskMessage taskMessage) async {
  sleep(Duration(seconds: 3));

  String res = 'onCompletedItem is ok';

  taskMessage.sendPort.send(TaskRes(taskMessage.taskItem.key, res));
}

Get up

2021-07-01 15:50:54.862973
2021-07-01 15:50:57.924675_onCompletedItem is ok
2021-07-01 15:50:57.954982_onCompletedItem is ok
2021-07-01 15:50:57.986042_onCompletedItem is ok
2021-07-01 15:50:58.021282_onCompletedItem is ok
2021-07-01 15:50:58.053387_onCompletedItem is ok
2021-07-01 15:50:58.088492_onCompletedItem is ok
2021-07-01 15:50:58.121968_onCompletedItem is ok
2021-07-01 15:50:58.157117_onCompletedItem is ok
2021-07-01 15:50:58.190835_onCompletedItem is ok
2021-07-01 15:50:58.229044_onCompletedItem is ok
2021-07-01 15:50:58.241011_onCompletedAll

It can be seen that the completion time of each task in the middle is very close, and the concurrent processing is perfect

to sum up

When many tasks need to be processed, multiple isolation areas can be opened up and executed concurrently to improve efficiency.

Dart language's handling of concurrency is still humane, it is not difficult to understand and easy to use.

Classmates, get up.


汤哥搞开发
34 声望4 粉丝