A coroutine can be defined as a generalized subroutine in Julia, which is a set of instructions stored in memory and invoked during execution.
As the Julia language has been created to provide faster computation, coroutines allow us to create multiple subroutines using the @task
macro. These tasks are then invoked by scheduling them through the schedule()
function. Unless the tasks are invoked, they stay in a runnable but dormant state.
Note: Coroutines are not a type of parallel processing. They simply allow the creation of more than one subroutines simultaneously.
using Distributedusing Base# Pell numbersfunction pell_generator(n)a, b = (0, 1)for i = 1:na, b = (b, 2 * b + a)endreturn a, bendgen1 = @task pell_generator(5)# Generator stateprintln("State of Pell generator: ", gen1.state)println("Has Pell generator started: ", istaskstarted(gen1))# Start Pell generatorprintln("\n-------------------Start Pell generator-------------------")schedule(gen1)yield()println("Has Pell generator started: ", istaskstarted(gen1))println("Pell sequence: ", gen1.result)println("State of Pell generator: ", gen1.state)
In this code example:
Lines 4–11: A function pell_generator(n)
is defined, which returns the Pell numbers after n
iterations.
Line 13: The function is wrapped in a task. This creates a subroutine.
Line 16: The current state of the generator is printed.
Line 17: It checks whether the task has started or not.
Line 21–22: The task is scheduled and executed.
Line 23: It checks if the task has started. The task has started now.
Line 25: The result of the generator function is displayed.
Line 26: The current state of the generator is printed.