Multithreading

You can find answers to those questions easily in the Julia Manual or by typing ? and then a command in the Julia REPL:

help?> Threads.@spawn
  Threads.@spawn expr

  Create and run a Task on any available thread. ...

help?> @async
  @async

  Wrap an expression in a Task and add it to the local machine's scheduler
  queue. ...

help?> @sync
  @sync

  Wait until all lexically-enclosed uses of @async, @spawn, @spawnat and
  @distributed are complete. ...

The Julia documentation is quite good, it gives quick answers … No worry!

@async starts a task on the same thread you are on, @spawn starts it on another thread. In your case you could go also with the @threads macro if you want be sure the queries all run in parallel on different threads (This is not guaranteed by @spawn). My example above would become then:

function parallel_query(n)
    ch = Channel(n)
    Threads.@threads for i in 1:n
        @async query(i, ch)
    end
    for i in 1:n
        res = take!(ch)
        println(res)
        !res[2] && break
    end
end

I put an additional @async here to make the @threads for ... loop return immediately after the queries have started on all threads.

2 Likes