Skip to content

Instantly share code, notes, and snippets.

@Shians
Created June 20, 2023 06:35
Show Gist options
  • Select an option

  • Save Shians/eb1032ea50766a956eb2814dcd07b524 to your computer and use it in GitHub Desktop.

Select an option

Save Shians/eb1032ea50766a956eb2814dcd07b524 to your computer and use it in GitHub Desktop.
# parallel iteration pattern for processing chunks of data in parallel
fetch_and_process <- function(get_data_chunk, process_func, reduce_func) {
n_workers <- future::nbrOfWorkers()
results <- list()
i <- 1
out_of_data <- FALSE
while(TRUE) {
for (. in 1:n_workers) {
chunk <- get_data_chunk()
if (is.null(chunk)) {
out_of_data <- TRUE
break
}
results[[i]] <- future::future({ process_func(chunk) })
i <- i + 1
}
lapply(results, value)
if (out_of_data) {
break
}
}
# Extract the results from the futures
results <- lapply(results, value)
purrr::reduce(results, reduce_func)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment