Dart语言教程:并发

2019-06-2217:45:31编程语言入门到精通Comments4,581 views字数 1304阅读模式

并发是同时执行多个指令序列。它涉及同时执行多个任务。
Dart使用Isolates作为并行工作的工具。dart:isolate包是Dart的解决方案,用于获取单线程Dart代码并允许应用程序更多地使用可用的硬件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

隔离(Isolates)顾名思义,是运行代码的独立单元。在它们之间发送数据的唯一方法是传递消息,就像在客户端和服务器之间传递消息的方式一样。隔离有助于程序利用多核微处理器开箱即用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

下面通过一个例子代码来更好地理解这个概念。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

import 'dart:isolate';  
void foo(var message){ 
   print('execution from foo ... the message is :${message}'); 
}  
void main(){ 
   Isolate.spawn(foo,'Hello!!'); 
   Isolate.spawn(foo,'Greetings!!'); 
   Isolate.spawn(foo,'Welcome!!'); 

   print('execution from main1'); 
   print('execution from main2'); 
   print('execution from main3'); 
}
Dart

这里,Isolate类的spawn方法用来与其余代码并行运行函数foospawn函数有两个参数 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

  • 催生功能
  • 将传递给衍生函数的对象。

如果没有对象传递给生成的函数,则可以传递NULL值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

这两个函数(foomain)可能不一定每次都以相同的顺序运行。无法保证foo何时执行以及何时执行main()。每次运行时输出都不同。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

输出1文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

execution from main1 
execution from main2 
execution from main3 
execution from foo ... the message is :Hello!!
Shell

输出2文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

execution from main1 
execution from main2 
execution from main3 
execution from foo ... the message is :Welcome!! 
execution from foo ... the message is :Hello!! 
execution from foo ... the message is :Greetings!!
Shell

从输出中,可以得出结论,Dart代码可以从运行代码中产生新的隔离,就像Java或C#代码可以启动新线程一样。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

隔离与线程的不同之处在于隔离区有自己的内存。没有办法在隔离区之间共享变量 - 隔离区之间通信的唯一方法是通过消息传递。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

注 - 对于不同的硬件和操作系统配置,上述输出将有所不同。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

隔离与Future文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

异步执行复杂的计算工作对于确保应用程序的响应性非常重要。Dart Future是一种在完成后检索异步任务的值的机制,而Dart Isolates是一种抽象并行性并在实际的高级基础上实现它的工具。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/dart/dart_programming_concurrency.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13773.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/13773.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定