# Race condition reading from Pipe

**URL:** <https://discourse.julialang.org/t/race-condition-reading-from-pipe/108707>\
**Category:** Internals & Design\
**Tags:** question, io, async\
**Created:** [January 11, 2024, 10:28pm UTC](https://discourse.julialang.org/t/race-condition-reading-from-pipe/108707 "2024-01-11T22:28:54Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![goerz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerz/32/3269_2.png) [@goerz](https://discourse.julialang.org/u/goerz)\
**Post date:** [January 11, 2024, 10:28pm UTC](https://discourse.julialang.org/t/race-condition-reading-from-pipe/108707/1 "2024-01-11T22:28:54Z")

</div>

Splitting this off from [A `tee` option for `IOCapture`](https://discourse.julialang.org/t/a-tee-option-for-iocapture/108642)

Does the following minimal working example for asynchronously reading data from a `Pipe` involve a race condition?

```julia
using Random

function main()

    pipe = Pipe()
    Base.link_pipe!(pipe; reader_supports_async=true, writer_supports_async=true)

    bufsize = 128
    buffer = Vector{UInt8}(undef, bufsize)
    buffer_redirect_task = @async begin
        while isopen(pipe)
            nbytes = readbytes!(pipe, buffer, bufsize)
            data = view(buffer, 1:nbytes)
            write(stdout, data)
        end
    end

    io = pipe.in
    for i = 1:10000
        write(pipe.in, randstring(64))
    end
    write(pipe.in, "[END OF STREAM]")
    close(pipe.in)

end

main()

```

Running the example, I haven’t been able to demonstrate one, in that I’m always seeing `[END OF STREAM]` printed to `stdout`. But my gut feeling would be that the main task might write data to the pipe and close it after `buffer_redirect_task` reads the data. Then, the `isopen` check would end the loop, losing the last data that was written.

Is there an asynchronous I/O expert who could confirm whether there is indeed a race condition here? If yes: How can I rewrite the example so that it is guaranteed to write all the data from the pipe to `stdout`? If not: _why_ is this safe?

---

<div class="post-metadata">

**Author:** ![goerz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerz/32/3269_2.png) [@goerz](https://discourse.julialang.org/u/goerz)\
**Post date:** [January 11, 2024, 11:10pm UTC](https://discourse.julialang.org/t/race-condition-reading-from-pipe/108707/2 "2024-01-11T23:10:24Z")

</div>

As suggested by @Sukera on Slack, the correct solution should be to replace `isopen(pipe)` with `!eof(pipe)`
