Behavior of `@time` when using `@spawn` (in Julia 1.8 highlights blog post)

Hi,

I was just reading the Julia 1.8 highlights blog post and I have a question about multithreading (a Julia feature I have never used).

In the section about the new default scheduler for @threads, there is the following example running on Julia 1.8:

julia> @time begin
            Threads.@spawn busywait(5)
            Threads.@threads for i in 1:Threads.nthreads()
                busywait(1)
            end
        end
2.012056 seconds (16.05 k allocations: 883.919 KiB, 0.66% compilation time)

Since the busywait(5) call should take 5 s to complete, I just want to be sure that I understand correctly the behavior of @time when using @spawn. My understanding of this code is that at the end of the timed block (which took 2s), the thread which runs busywait(5) is not finished (and will take ~3s to complete). Am I right?

2 Likes

Yes, that is correct. We can test your hypothesis by slightly modifying your example:

julia> @time begin
           t = time()
           Threads.@spawn (busywait(5); println(time() - t))
           Threads.@threads for i in 1:Threads.nthreads()
               busywait(1)
           end
       end
  2.062341 seconds (43.90 k allocations: 2.938 MiB, 3.01% compilation time)

julia> 5.037096977233887 # printed after the 5s have passed
2 Likes

Thanks!