# Handy function to print the session states all at once.
check_state <- function(session) {
# Create a session object and determine its state.
session_state <- SessionState$new(session)
# Print the state.
cat(
"Session is starting: ", session_state$session_is_starting, "\n",
"Session is idle: ", session_state$session_is_idle, "\n",
"Session is busy: ", session_state$session_is_busy, "\n",
"Session is finished: ", session_state$session_is_finished, "\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 session is idle.
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 that the session is busy.
check_state(backend$cluster)
}
# Get the output and wait for the task to complete.
output <- backend$get_output(wait = TRUE)
# Check that the session is idle again.
check_state(backend$cluster)
# Manually close the session.
backend$cluster$close()
# Check that the session is finished.
check_state(backend$cluster)
# Stop the backend.
backend$stop()
Run the code above in your browser using DataLab