# Threaded screen I/O

**URL:** <https://discourse.julialang.org/t/threaded-screen-i-o/29474>\
**Category:** General Usage\
**Created:** [October 4, 2019, 7:40am UTC](https://discourse.julialang.org/t/threaded-screen-i-o/29474 "2019-10-04T07:40:55Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ckoe-bccms](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ckoe-bccms/32/1816_2.png) [@ckoe-bccms](https://discourse.julialang.org/u/ckoe-bccms)\
**Post date:** [October 4, 2019, 7:40am UTC](https://discourse.julialang.org/t/threaded-screen-i-o/29474/1 "2019-10-04T07:40:55Z")

</div>

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
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
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

```julia
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
