猫中的异步可以并行吗?

Sim*_*mY4 2 scala scala-cats

Parallel我注意到,即使在最强大的 typeclass 中,cats-effect 类型类层次结构也不会从 cats 核心继承ConcurrentEffect。仅当直接使用 IO 时,才存在为并行提供的唯一实例。

但不应该有一个吗?我有点觉得Sync[F]并且Async[F]应该是一个很好的二人组Parallel[F]

Mat*_*zok 5

该行为与层次结构所承诺Parallel的确实不同(即顺序但(a)同步执行)。承诺您的计算在线程池上运行并且可以取消(+其较小元素承诺的所有内容) - 仍然无法组合并行计算,但允许您实现竞争。是正交语义,这就是它作为单独的类型类/类型约束传递的原因。因此只需将其添加为单独的类型约束即可。SyncAsyncConcurrentEffectParallel

def toStringParallel[F[_]: Sync: Parallel](list: List[F[Int]]): F[List[String]] =
  list.parTraverse(a => a.toString.pure[F])

object App1 extends IOApp {
  def run(args: List[String]) = toStringParallel[IO](List(IO(1), IO(2)))
    .as(ExitCode.Success)
}
Run Code Online (Sandbox Code Playgroud)

如果您无法实例化Parallel[IO],请记住它需要ContextShift[IO]创建 Parallel[IO] 的实例

// example from docs
implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

val ioA = IO(println("Running ioA"))
val ioB = IO(println("Running ioB"))
val ioC = IO(println("Running ioC"))

// make sure that you have an implicit ContextShift[IO] in scope. 
val program = (ioA, ioB, ioC).parMapN { (_, _, _) => () }
Run Code Online (Sandbox Code Playgroud)