How to do a timedwait on a ReentrantLock or Threads.Condition

Is it possible to do a timedwait on a ReentrantLock or Threads.Condition?

rlock = ReentrantLock()

timedwait(rlock, 5)

I suppose you could do something like that:

struct CheckOnLock
    lck::ReentrantLock
end

# the `function (foo::Bar)(args...; kwargs...) ... end` syntax creates a
# method that is called upon calling `foo(args...; kwargs...)`, where `foo` is
# a value of type `Bar`
function (x::CheckOnLock)()
    return !islocked(x.lck)
end

timedwait(CheckOnLock(rlock), 5)

If you want to keep the lock when timedwait succeeds, then you should use the function:

(x::CheckOnLock)() = trylock(x.lck)

instead of the function (x::CheckOnLock)() ... above.

1 Like