gpt4 book ai didi

r - mclapply 是否保证按顺序返回其结果?

转载 作者:行者123 更新时间:2023-12-03 23:43:02 25 4
gpt4 key购买 nike

我正在与 mclapply 一起工作来自 multicore包(在 Ubuntu 上),我正在编写一个函数,该函数要求 mclapply(x, f) 的结果按顺序返回(即 f(x[1]), f(x[2]), ...., f(x[n]) )。

# multicore doesn't work on Windows

require(multicore)
unlist(mclapply(
1:10,
function(x){
Sys.sleep(sample(1:5, size = 1))
identity(x)}, mc.cores = 2))

[1] 1 2 3 4 5 6 7 8 9 10

上面的代码似乎暗示 mclapply以与 lapply 相同的顺序返回结果.

但是,如果这个假设是错误的,我将不得不花很长时间重构我的代码,所以我希望从更熟悉这个包/并行计算的人那里得到保证,这个假设是正确的。

假设 mclapply 是否安全?无论给出的可选参数如何,总是按顺序返回其结果?

最佳答案

简短回答:它确实以正确的顺序返回结果。

但当然,你应该自己阅读代码(mclapply 是一个 R 函数......)
collect 的手册页给出了更多提示:

Note: If expr uses low-level multicore functions such as sendMaster a single job can deliver results multiple times and it is the responsibility of the user to interpret them correctly.



但是,如果你不惹低级,

collect returns any results that are available in a list. The results will have the same order as the specified jobs. If there are multiple jobs and a job has a name it will be used to name the result, otherwise its process ID will be used.



(我的重点)

现在为 mclapply .
快速浏览一下源代码会得到:
  • 如果 !mc.preschedule并且没有比核心更多的工作( length (X) <= cores )parallelcollect使用,见上文。
  • 如果 mc.preschedule或比核心更多的工作,mclapply本身负责顺序 - 请参阅代码。

  • 但是,这是对您的实验稍加修改的版本:
    > unlist (mclapply(1:10, function(x){
    Sys.sleep(sample(1:5, size = 1));
    cat (x, " ");
    identity(x)},
    mc.cores = 2, mc.preschedule = FALSE))
    1 2 4 3 6 5 7 8 9 10 [1] 1 2 3 4 5 6 7 8 9 10
    > unlist (mclapply(1:10, function(x){
    Sys.sleep(sample(1:5, size = 1));
    cat (x, " ");
    identity(x)},
    mc.cores = 2, mc.preschedule = TRUE))
    1 3 2 5 4 6 7 8 10 9 [1] 1 2 3 4 5 6 7 8 9 10

    这表明子作业以不同的顺序返回结果(更准确地说:子作业将以不同的顺序完成),但结果是按原始顺序组装的。

    (适用于控制台,但不适用于 RStudio - cat 不显示在那里)

    关于r - mclapply 是否保证按顺序返回其结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14697901/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com