Talking about how Dart realizes multi-task parallelism

 

Dart is a programming language that supports multitasking and parallelism, and it provides a variety of mechanisms to achieve concurrency and parallelism. Here are several ways Dart implements multitasking parallelism:

Isolate in Dart is a lightweight concurrency mechanism, similar to threads. Each isolated area is an independent memory space, and each isolated area has its own memory space and execution thread, so codes can be executed independently between different isolated areas, and each isolated area runs on its own core, Will not block other Isolates. Thus achieving concurrency. But one thing to note is that data cannot be shared directly between them, it must be achieved through message passing.

Here is a simple sample code showing how to use Isolate to achieve concurrent execution in Dart:

1

2

3

4

5

6

7

8

9

10

11

12

import 'dart:isolate';

void main() async {

  // 创建两个隔离区域

  final isolate1 = await Isolate.spawn(runIsolate, 1);

  final isolate2 = await Isolate.spawn(runIsolate, 2);

  // 等待隔离区域执行完毕

  await Future.wait([isolate1.exitCode, isolate2.exitCode]);

}

void runIsolate(int id) {

  // 隔离区域中执行的代码

  print('Isolate $id is running');

}

In the above example, we first use the Isolate.spawn function to create two isolation areas, and each isolation area will execute the runIsolate function and pass in different parameters (1 and 2). The runIsolate function is the actual code executed in the isolate, it simply prints a message.

After creating the isolation area, we use the Future.wait function to wait for the isolation area to complete. Here the exitCode property returns the exit code of the isolate, it will return 0 if the code executes successfully.

When we run the above code, we will see the following output:

Isolate 1 is running
Isolate 2 is running

It can be seen that the two isolated areas are started and executed almost at the same time, achieving the effect of concurrent execution. This is just a simple example of Isolate, you can use it to perform more complex concurrent tasks, such as using multiple Isolates to download multiple files at the same time, or perform computationally intensive tasks in different isolated areas to improve performance, etc.

async/await

In Dart, async/await uses Future objects to implement asynchronous operations. When we add the async keyword in front of a function or method, the function becomes an asynchronous function. The await keyword can be used in an asynchronous function to wait for the results of other asynchronous operations without blocking the execution of the current function.

The following is a demo code that uses async/await to achieve asynchronous concurrency. It will download the contents of two URLs at the same time, and print the results after both download operations are completed:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import 'dart:async';

import 'dart:convert';

import 'dart:io';

Future<void> main() async {

  final url1 = 'https://www.example.com';

  final url2 = 'https://www.example.net';

  final result1 = downloadUrl(url1);

  final result2 = downloadUrl(url2);

  final results = await Future.wait([result1, result2]);

  for (final result in results) {

    print(result);

  }

}

Future<String> downloadUrl(String url) async {

  final httpClient = HttpClient();

  final request = await httpClient.getUrl(Uri.parse(url));

  final response = await request.close();

  final contents = await response.transform(utf8.decoder).join();

  httpClient.close();

  return contents;

}

In the above code, the downloadUrl method is an asynchronous function that downloads the content of the given URL using the HttpClient class. In the main function, we use the Future.wait method to wait for both download operations to complete, and then print the results. Since result1 and result2 are performed at the same time, the whole process is concurrent.

Stream

Stream in Dart is an event-based asynchronous programming model that can handle a continuous stream of asynchronous events. Using Stream, a long-running task can be decomposed into multiple small tasks, and the results can be pushed into the event stream after each small task is completed, so that other tasks can get the results asynchronously.

The following is a demo code that uses Stream to implement asynchronous concurrency, which downloads data from two URLs and prints the results:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import 'dart:async';

import 'dart:convert';

import 'dart:io';

Future<void> main() async {

  final url1 = 'https://www.example.com';

  final url2 = 'https://www.example.net';

  final stream1 = downloadUrl(url1);

  final stream2 = downloadUrl(url2);

  await for (final result in StreamGroup.merge([stream1, stream2])) {

    print(result);

  }

}

Stream<String> downloadUrl(String url) async* {

  final httpClient = HttpClient();

  final request = await httpClient.getUrl(Uri.parse(url));

  final response = await request.close();

  await for (final chunk in response.transform(utf8.decoder)) {

    yield chunk;

  }

  httpClient.close();

}

In the above code, the downloadUrl method returns a Stream object for asynchronously downloading the content of the given URL. In the main function, we use the StreamGroup.merge method to merge the two download streams into one, and use the await for loop to process the download results one by one.

It should be noted that in the downloadUrl method, we use the yield keyword to send the downloaded data blocks to the Stream one by one, so that the data can be sent out continuously during the download process without waiting until all the data is downloaded Send again in one go. This is also one of the advantages of Stream when dealing with a large number of asynchronous events.

Compute Function

A Compute Function in Dart is a function that can run in an independent Isolate, which can receive input parameters and return results. Using Compute Function can decompose a calculation-intensive task into multiple small tasks, use Compute Function in each small task to calculate the results in parallel, and finally combine the results.

下面是一个使用Compute Function实现异步并发的Demo代码,它会计算两个斐波那契数列,并将结果打印出来:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import 'dart:async';

import 'package:flutter/foundation.dart';

Future<void> main() async {

  final result1 = compute(fibonacci, 40);

  final result2 = compute(fibonacci, 41);

  final results = await Future.wait([result1, result2]);

  for (final result in results) {

    print(result);

  }

}

int fibonacci(int n) {

  if (n == 0) return 0;

  if (n == 1) return 1;

  return fibonacci(n - 1) + fibonacci(n - 2);

}

在上面的代码中,我们使用compute函数将斐波那契数列的计算任务交给后台隔离线程执行,然后使用Future.wait方法等待两个任务都完成后打印结果。

需要注意的是,在使用compute函数时,传递给它的函数必须是顶层函数或静态函数,因为后台隔离线程无法访问非静态变量或实例变量。

总的来说,Dart 提供了多种机制来实现多任务并行,包括 Isolate、async/await、Stream 和 Compute Function。这些机制可以根据具体的任务需求选择使用,从而实现高效的并发和并行。

以上就是一文详解Dart如何实现多任务并行的详细内容,希望可以帮到你。

转自:微点阅读   https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131864142