Hello everybody,
I was trying the threading in 1.3rc2 and there are some questions regarding (screen) I/O which came up and which I could not directly answer using google.
Apparently @printf does not “lock” the screen, i.e.
julia> Threads.@threads for ii=1:6
@printf("%i %e\n",Threads.threadid(),rand())
end
12 85..469240174250ee--01
2 2.494711e-01
2 6.961889e-01
01
1 3.814460e-01
1 6.575211e-01
which is obviously garbled. There is no locking ?
One solution I came up with after some googling is
julia> mutex=Threads.SpinLock()
Base.Threads.SpinLock(Base.Threads.Atomic{Int64}(0))
julia> Threads.@threads for ii=1:6
lock(mutex)
@printf("%i %e\n",Threads.threadid(),rand())
unlock(mutex)
end
1 2.133481e-01
2 2.833172e-01
1 8.236247e-01
1 4.356400e-01
2 6.385873e-01
2 5.719459e-01
This appears to work. However, I am not sure if I am doing the right thing and if I use the right locking mechanism (the actual code is called non-recursive) ?
Also, perhaps there is already a locking @printf
equivalent function ? Or is it sensible to write a general function along the lines of
function locking_printf(mutex, format_string, args)
lock(mutex)
@printf(format_string,args)
unlock(mutex)
end
Finally, what about file I/O using @printf(file_handle,...)
? I assume I also need to lock that ?
Best Regards