dart的多线程

文章介绍了Dart中处理并发的三种方式:使用Isolate直接创建并发线程,通过管道进行通信,以及使用compute函数简化后台计算。示例代码展示了如何在后台Isolate中执行计算密集型任务,如计算斐波那契数列,并返回结果。

通过Isolate

import 'dart:isolate';

void main(List<String> args) {
  print('strat');
  //开启一个并发线程
  Isolate.spawn(cldc, 100);
  print('end');
}

void cldc(int count) {
  int tolte = 0;
  for (int i = 0; i < count; i++) {
    tolte = tolte + i;
  }
  print(tolte);
}

通过管道

import 'dart:isolate';
 
void main(List<String> args) async{
  print('strat');
  //1.创建管道
  ReceivePort receivePort=ReceivePort();

  //2.创建Isolate
  Isolate isolate=await Isolate.spawn<SendPort>(cldc,receivePort.sendPort);

  //3.监听管道
  receivePort.listen((message) {
    print(message);
    receivePort.close();
    isolate.kill();
  },);

  print('end');
}
 
void cldc(SendPort send) {
  int tolte = 0;
  for (int i = 0; i < 100; i++) {
    tolte = tolte + i;
  }
  return send.send(tolte);
}

使用compute

compute 是一个方便的函数,用于在后台 Isolate 中执行计算密集型的任务,并返回结果给调用者。它简化了在 Isolate 之间传递消息和处理并发任务的过程。

compute 函数接受两个参数:一个是要在后台执行的函数,另一个是该函数的输入参数。它会自动创建和管理一个新的 Isolate,并将输入参数传递给该函数。当函数执行完毕后,结果会被返回给调用者。

import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

main() {
  print('main start');
  runApp(MyApp());

  int fibonacci(int n) {
    if (n == 0 || n == 1) {
      return n;
    } else {
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
  }

  void com() async {
    int result = await compute(fibonacci, 10);
    print('Fibonacci result: $result');
  }
  com();
  print('main end');
}

我们定义了一个计算斐波那契数列的函数 fibonacci,然后使用 compute 函数以参数 10 调用它。compute 函数会在后台 Isolate 中执行 fibonacci 函数,并返回结果给调用者。最后,我们打印出计算的结果。

使用 compute 的好处是它抽象了与 Isolate 的通信细节,让我们可以专注于编写计算密集型的函数逻辑,而无需担心并发和消息传递的细节。它可以提高应用程序的性能,并让异步任务更加方便和易于管理。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值