[英]Can there be Parallel for Async in cats effect?
I noticed that cats-effect typeclass hierarchy doesn't inherit Parallel
from cats core even at their most powerful typeclass ConcurrentEffect
.我注意到即使在最强大的类型类ConcurrentEffect
,cats-effect typeclass 层次结构也没有从cats 核心继承Parallel
。 The only instance provided for parallel exists only if you use IO directly.只有当您直接使用 IO 时,才存在为并行提供的唯一实例。
But shouldn't there be one?但不应该有一个吗? I kinda feel like Sync[F]
and Async[F]
should be a nice duo for Parallel[F]
.我有点觉得Sync[F]
和Async[F]
应该是Parallel[F]
的好搭档。
The Parallel
behavior is really different to what Sync
and Async
hierarchy promises (that is sequential but (a)synchronous execution). Parallel
行为与Sync
和Async
层次结构所承诺的(即顺序但(a)同步执行)确实不同。 ConcurrentEffect
promises that your computation runs on a thread pool and can be cancelled (+ everything its smaller elements promise) - still not enable combining parallel computations but allows you to implement races. ConcurrentEffect
承诺您的计算在线程池上运行并且可以取消(+ 其较小元素承诺的所有内容)-仍然不能组合并行计算,但允许您实现竞争。 Parallel
is an orthogonal semantics which is why it is passed as a separate type class/type constraint. Parallel
是一种正交语义,这就是为什么它作为单独的类型类/类型约束传递的原因。 So just add it as a separate type constraint.所以只需将其添加为单独的类型约束。
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)
}
If you cannot instantiate Parallel[IO]
, remember that it requires ContextShift[IO]
to create an instant of Parallel[IO] .如果您无法实例化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 { (_, _, _) => () }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.