# Handy function to print the task states all at once.
check_state <- function(session) {
# Create a task state object and determine the state.
task_state <- TaskState$new(session)
# Print the state.
cat(
"Task not started: ", task_state$task_not_started, "\n",
"Task is running: ", task_state$task_is_running, "\n",
"Task is completed: ", task_state$task_is_completed, "\n",
sep = ""
)
}
# Create a specification object.
specification <- Specification$new()
# Set the number of cores.
specification$set_cores(cores = 2)
# Set the cluster type.
specification$set_type(type = "psock")
# Create an asynchronous backend object.
backend <- AsyncBackend$new()
# Start the cluster on the backend.
backend$start(specification)
# Check that the task has not been started (i.e., the backend is free).
check_state(backend$cluster)
{
# Run a task in parallel (i.e., approx. 0.25 seconds).
backend$sapply(
x = 1:10,
fun = function(x) {
# Sleep a bit.
Sys.sleep(0.05)
# Compute something.
output <- x + 1
# Return the result.
return(output)
}
)
# And immediately check the state to see that the task is running.
check_state(backend$cluster)
}
# Sleep for a bit to wait for the task to complete.
Sys.sleep(1)
# Check that the task is completed (i.e., the output needs to be retrieved).
check_state(backend$cluster)
# Get the output.
output <- backend$get_output(wait = TRUE)
# Check that the task has not been started (i.e., the backend is free again).
check_state(backend$cluster)
# Stop the backend.
backend$stop()
Run the code above in your browser using DataLab