June 2019
Intermediate to advanced
218 pages
5h 19m
English
Consider the following trivial code. How long do you think this will take?
for i in 1:5 sleep(1)end
Well, the answer is obviously five seconds—a sleep of one second at a time, executed five times, as shown in the following code:
julia> @time for i in 1:5 sleep(1) end 5.026456 seconds (26 allocations: 1.266 KiB)
Now see what happens when we write this code with the @async macro, as follows:
julia> @time for i in 1:5 @async sleep(1) end 0.000140 seconds (32 allocations: 4.375 KiB)
The @async macro (short for asynchronous) creates and schedules tasks for all code within its scope (in this case, the sleep(1) function call), which means all the sleep calls happen in separate tasks. The for loop, which is running on the REPL task, returns ...
Read now
Unlock full access