Dart,完成消息处理,并发保证澄清

问题描述 投票:0回答:1

dart 并发的背景下进行讨论。

问题是从多线程编程的思维方式提出的,不能保证并发状态更改何时会发生,以及随之而来的需要管理各种可能的状态更改的同步。例如:

class Outbox{

 static final _queue = Queue<Order>();


 static void _processQueueAsync() async {

  /* block1
  no await, Future in this block.

  in multithreading platform _queue can be modified (orders added/removed) 
  while this block is executing either by 
  1.1 a parallel thread; or
  1.2 suspending present thread at any point, switching to another thread and then back

  in dart _queue will not be altered while this block executes, because:
  2.1 while parallel isolate may be executing, unlike multithreading, 
      its memory is a separate instance (though possibly executing the same lexical scope) 
  2.2 current isolate keeps UNINTERRUPTED execution of the code path triggered 
      by the event loop message until the execution path completes. 
      note, "completion" includes returning Future or async/await (not the case in block1). 
      thus, unlike in multi-threading platform, dart guarantees un-interrupted 
      execution of this block. 
  end block1 */

  // block2
  await ShipAsync(order);
  /*
  From the moment above await kicks in and until it resolves (which time-wise is a subset of 
  "until the next line") _queue can be altered even in dart 
  ( including by a code outside of SendAsync() ). 
  one way to think about it, as if old message execution path completed with previous line 
  and subsequent execution is triggered by "a new message" of resolving above await/Future.
  */
  return;
 }

}

我的问题是关于

block1
中无并发状态更改(记忆当前隔离)的 dart 保证。文档非常清楚地表明分离株具有单独的内存(
2.1
),这是所需的两个前提之一。但是不中断保证(
2.2
),我还没有明确看到。我认为它隐含在文档描述 dart 并发性的方式中,但希望得到确认。

问题:dart 是否保证由循环中的消息触发一路不间断地执行路径,直到完成该路径(保存

await
Future
)?例如,它不像一条消息的路径执行(例如,屏幕点击的 UI 更新)可以暂停,执行会切换到另一条消息触发的不同路径(例如,计时器或流已勾选),然后切换回之前的路径。这就是多线程。

目标:在

dart
中,无需担心
block1
类型的词汇延伸中的并发状态变化(与
java
/
c#
等多线程平台不同)。

dart concurrency
1个回答
0
投票

函数中标记为 block1 的代码

_processQueueAsync()
保证同步运行。

一般来说,

async
函数同步运行,直到遇到第一个
await
语句。

这意味着在

async
函数体内,第一个await关键字之前的所有同步代码都会立即执行。

更多详情请参阅:async 和await 的执行流程。

© www.soinside.com 2019 - 2024. All rights reserved.