在 Scala 中,as explained in the PR that introduced it , parasitic
允许偷窃
execution time from other threads by having its
Runnable
s run on theThread
which callsexecute
and then yielding back control to the caller after all itsRunnable
s have been executed.
在以下情况下避免上下文切换似乎是一个巧妙的技巧:
Future
进行微不足道的操作来自实际长时间运行的操作,或 ExecutionContext
对于 Future
但是您希望确保操作在同一线程上继续进行,而不引入不同的线程池 原先介绍的 PR
parasitic
further explains那When using
parasitic
with abstractions such asFuture
it will in many cases be non-deterministic as to whichThread
will be executing the logic, as it depends on when/if thatFuture
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 indoSomething
’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
完成得非常快,它可能会将控制权返回给主线程,而您最终可能实际上没有运行 doSomethingElse
在 global
线程,但在主要的。这就是我能做到的,但我想确认一下。 Future
的惰性实现抽象(例如 IO
在 Cats 中)可以使这更容易和可靠,但我想了解这是否可以使用 Future
来自标准库。 最佳答案
parasitic
对堆栈递归有一个上限,以尝试降低由于嵌套提交而导致的 StackOverflowError 风险,并且可以将 Runnable 推迟到队列中。 我发现将 Futures 视为在特定时间点可能存在或可能不存在的值的读取句柄更容易。这很好地从图片中解开了线程的概念,现在它是关于:当一个值可用时,我想做 X——这是将做 X 的 ExecutionContext。
关于multithreading - 同步执行上下文的不确定性(又名 `parasitic`),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61792512/