How does io redirection work with tasks?

I don’t understand this simple MWE:

julia> redirect_stdio(;stdout = devnull) do
           @async println("hello")
           @async redirect_io(; stdout = devnull) do
               println("hey")
           end
           println("hi")
       end
hello

The docstring of redirect_stdio doesn’t mention anything about it not affecting child tasks. How does this actually work?

3 Likes

The do block seems to complete without interruption, the streams restored, and then the tasks run. If you do something to interrupt the do block and go to the scheduler:

julia> redirect_stdio(;stdout = devnull) do
           @async println("hello")
           sleep(0)
           @async redirect_io(; stdout = devnull) do
               println("hey")
           end
           println("hi")
       end

My preference is to never let a block return if tasks created in that block are still running.

julia> Base.redirect_stdio(;stdout = devnull) do
               @sync begin
                  @async println("hello")
                  @async Base.redirect_stdio(; stdout = devnull) do
                      println("hey")
                  end
                  println("hi")
               end
              end

julia> 
2 Likes