What Are coroutines In Julia?

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.

Code Example

using Distributed
using Base
# Pell numbers
function pell_generator(n)
a, b = (0, 1)
for i = 1:n
a, b = (b, 2 * b + a)
end
return a, b
end
gen1 = @task pell_generator(5)
# Generator state
println("State of Pell generator: ", gen1.state)
println("Has Pell generator started: ", istaskstarted(gen1))
# Start Pell generator
println("\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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved