Here’s a small example of the channel-based approach:
using Base.Threads
channel = Channel{Task}(Inf)
function consumer(channel::Channel)
while true
task = take!(channel)
schedule(task)
wait(task)
end
end
worker1 = @spawn consumer(channel)
worker2 = @spawn consumer(channel)
With tasks:
put!(channel, @task println("Hello, world!"))
put!(channel, @task println("Goodbye, world!"))
put!(channel, @task (sleep(2); println("Task 2 seconds")))
put!(channel, @task println(sum(1:1000)))
When I add the tasks in the REPL:
julia> put!(channel, @task println("Hello, world!"))
Task (runnable) @0x000000011b71de40
julia> put!(channel, @task println("Goodbye, world!"))
Hello, world!
Task (runnable) @0x000000011b71e230
julia> put!(channel, @task (sleep(2); println("Task 2 seconds")))
Goodbye, world!
Task (runnable) @0x000000011b71e620
julia> put!(channel, @task println(sum(1:1000)))
Task (runnable) @0x000000011b71eb60
julia> 500500
Task 2 seconds