Channel take if available

Hi all :slight_smile:

Is there a way to take an element from a Channel if and only if there are elements available. This should be non blocking.

I could do something like:

julia> c = Channel(10)
Channel{Any}(10) (empty)

julia> !isempty(c) && take!(c)

julia> put!(c, :element)

julia> !isempty(c) && take!(c)

But this is not thread safe. Because after !isempty(c) is called a different thread could wake up and take from c

Looks like we do not have such function yet based on the last paragraph in add maybetake! and tryput! by tkf · Pull Request #41966 · JuliaLang/julia · GitHub

Note also that this PR does not implement the “non-blocking” version of put/take. However, it is conceivable to add maybetake_nowait! and tryput_nowait! in the future (with a warning in the docstring that they are “racy” APIs and it is discouraged to use them, unless you know what you are doing.)

1 Like