Ah, do what @mauro3 says: Core.println
For interest:
In your result, there are only 15 outputs rather than 20.
Ah yes, because there are some left in the pending
queue but thread1 is done with its printing.
Solution is the check anything left pending after the loop is done.
It should only be about 1 thing for each thread, if the threads are doing roughly equal work.
Another thing is all the 15 outputs here are printed out together after the entire loop finished.
I do not see this.
Perhaps in the small example, of just 20 thins with no delay between then it looked that way?
In the example below I’ve added some code to make them take some time.
and it is clear that it is happening every time thread1 runs.
not just at the end
Code
using Base.Threads
const print_lock = SpinLock()
const pending_prints = Vector{String}()
function print_pending()
@assert Threads.threadid() == 1
println.(pending_prints)
empty!(pending_prints)
end
function tprintln(str)
tid= Threads.threadid()
str = "[Thread $tid]: " * string(str)
lock(print_lock) do
push!(pending_prints, str)
if tid == 1 # Only first thread is allows to print
print_pending()
end
end
end
Demo
function busy_sleep(time) # Base.sleep is not threadsafe
start = now()
x=0
while(now()-start < Dates.Millisecond(time))
end
end
Threads.@threads for ii in 1:100
busy_sleep(50+ii)
tprintln(ii) # use our new function
end
print_pending() # get any prints that are still not done