How to wait for a thread to complete

I think you’d be better off using a Channel (rather than a Condition) for this:

using Base.Threads: @spawn, threadid

function post_process(message, chan)
    println("post processing $message on thread $(threadid())")
    # simulated processing
    sleep(2)
    result = :outgoing_message
    put!(chan, result)
    println("post processing complete on thread $(threadid())")
end

function reply(chan)
    while true
        result = take!(chan)
        println("reply $(result) on thread $(threadid())")
    end
end

chan = Channel{Symbol}(32)

# run this once to wait for post_process
task = @async reply(chan)

message1 = " my received message 1"
# process message
@spawn post_process(message1, chan)

message2 = " my received message 2"
# process message
@spawn post_process(message2, chan)

wait(task)
$ julia -t 4 foo.jl 
post processing  my received message 1 on thread 2
post processing  my received message 2 on thread 3
reply outgoing_message on thread 1
reply outgoing_message on thread 1
post processing complete on thread 2
post processing complete on thread 3
^C
2 Likes