我注意到cats-effect类型类层次结构不会从cats核心继承Parallel,即使在它们最强大的类型类ConcurrentEffect中也是如此。仅当您直接使用IO时,才会存在为并行提供的唯一实例。
但是不是应该有一个吗?我觉得Sync[F]和Async[F]应该是Parallel[F]的好组合。
发布于 2020-09-04 19:19:22
Parallel行为实际上与Sync和Async层次结构承诺的不同(即顺序执行,但(A)同步执行)。ConcurrentEffect承诺你的计算在线程池上运行,并且可以取消(+它的更小的元素承诺的所有东西)-仍然不能组合并行计算,但允许你实现竞速。Parallel是一种正交语义,这就是为什么它被作为单独的类型类/类型约束传递。所以只需将其作为单独的类型约束添加即可。
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)
}如果不能实例化Parallel[IO],请记住it requires ContextShift[IO] to create an instant of 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 { (_, _, _) => () }https://stackoverflow.com/questions/63739243
复制相似问题