Tasks & Channels
Tasks are ideal for I/O concurrency (downloads, servers, timers).
27.1 Tasks (coroutines / green threads)
Tasks are ideal for I/O concurrency (downloads, servers, timers).
t = @async begin # schedule a Task on the current thread
sleep(1)
"done"
end
fetch(t) # wait and get the result
istaskdone(t)
@sync begin # wait for all tasks in the block
@async (sleep(1); println("A"))
@async (sleep(1); println("B"))
end # ~1 second total
t = Task(() -> println("manual")); schedule(t); wait(t)
errormonitor(@async error("surfaced")) # print errors of background tasks27.2 Channels (producer/consumer)
ch = Channel{Int}(10) # buffered channel
@async begin
for i in 1:5
put!(ch, i^2)
end
close(ch)
end
for v in ch # iterate until closed
println(v)
end
producer = Channel() do c # producer function form
for i in 1:3; put!(c, i); end
end
collect(producer)27.3 Timers, events, synchronization
Timer(t -> println("tick"), 0; interval=1) # periodic timer
cond = Threads.Condition(); ev = Base.Event()
lock(l) do ... end; ReentrantLock(); Base.Semaphore(3)
timedwait(() -> isready(ch), 5.0)