multithreading - 同步执行上下文的不确定性(又名 `parasitic`)

标签 multithreading scala concurrency

在 Scala 中,as explained in the PR that introduced it , parasitic允许偷窃

execution time from other threads by having its Runnables run on the Thread which calls execute and then yielding back control to the caller after all its Runnables have been executed.



在以下情况下避免上下文切换似乎是一个巧妙的技巧:
  • 您正在对 Future 进行微不足道的操作来自实际长时间运行的操作,或
  • 您正在使用的 API 不允许您指定 ExecutionContext对于 Future但是您希望确保操作在同一线程上继续进行,而不引入不同的线程池

  • 原先介绍的 PR parasitic further explains

    When using parasitic with abstractions such as Future it will in many cases be non-deterministic as to which Thread will be executing the logic, as it depends on when/if that Future is completed.



    Scala 官方文档中关于Synchronous Execution Contexts 的段落中也重复了这个概念。 :

    One might be tempted to have an ExecutionContext that runs computations within the current thread:

    val currentThreadExecutionContext = ExecutionContext.fromExecutor(
      new Executor {
        // Do not do this!
        def execute(runnable: Runnable) { runnable.run() }
    })
    

    This should be avoided as it introduces non-determinism in the execution of your future.

    Future {
      doSomething
    }(ExecutionContext.global).map {
      doSomethingElse
    }(currentThreadExecutionContext)
    

    The doSomethingElse call might either execute in doSomething’s thread or in the main thread, and therefore be either asynchronous or synchronous. As explained here a callback should not be both.



    我有几个疑问:
  • 怎么样parasitic与 Scala 文档中的同步执行上下文不同?
  • 两个来源中提到的非确定性的来源是什么?来自介绍 parasitic 的 PR 中的评论听起来好像 doSomething完成得非常快,它可能会将控制权返回给主线程,而您最终可能实际上没有运行 doSomethingElseglobal线程,但在主要的。这就是我能做到的,但我想确认一下。
  • 是否有一种可靠的方法可以让计算与其前一个任务在同一线程上运行?我想使用 Future 的惰性实现抽象(例如 IO 在 Cats 中)可以使这更容易和可靠,但我想了解这是否可以使用 Future来自标准库。
  • 最佳答案

  • parasitic对堆栈递归有一个上限,以尝试降低由于嵌套提交而导致的 StackOverflowError 风险,并且可以将 Runnable 推迟到队列中。
  • 不确定性的来源是:如果 Future 尚未完成:它将注册以在完成线程上运行。如果 Future 完成,它将在注册线程上运行。由于这两种情况可能取决于时间,因此无法确定哪个线程将执行代码。
  • 你怎么知道 A)这是哪个线程,以及 B)它是否能够再次执行另一个任务?

  • 我发现将 Futures 视为在特定时间点可能存在或可能不存在的值的读取句柄更容易。这很好地从图片中解开了线程的概念,现在它是关于:当一个值可用时,我想做 X——这是将做 X 的 ExecutionContext。

    关于multithreading - 同步执行上下文的不确定性(又名 `parasitic`),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61792512/

    相关文章:

    objective-c - 如何使用 Objective-C 获取正在运行的进程

    c - 如何停止C process.h中的特定线程?

    scala - 结合 `OptionT` 和 `EitherT` 来处理 `Future[Either[Error, Option[T]]]`

    c# - 如何合并多个异步调用的结果

    concurrency - 如何处理库存和并发

    concurrency - 消息传递与锁定

    java - 重绘在线程中不起作用

    python - 线程化快速创建大量图表

    scala - partition 和 groupBy 有什么区别?

    scala - 如何防止Hadoop的HDFS API创建父目录?