Equivalent of Python threading.Event for sync Rust

A simple and useful synchronization primitive in Python is threading.Event. It's basically a boolean flag that can be written to and read from an arbitrary number of threads, but it is also possible to block and wait with a timeout until the flag is set.

I am trying to find a similar concurrency primitive in sync Rust, but so far have not found anything straightforward. I would appreciate any recommendations.

It looks like you could build it pretty trivially with a Mutex<bool> and Condvar if an existing implementation doesn't already exist.

1 Like

I'm not python developer, but from your description, the python threading.Event is not like a "simple" primitive in lower level languages.

that's just a core::AtomicBool, and is available on (almost?) all CPUs, and doesn't require an OS system call.

this is how the std::CondVar can be used. but CondVar must be combined with a Mutex.

what you described can be achieved using the combination of the two:

  • apprach 1: combination of Mutex<bool> and CondVar
  • apprach 2: combination of Mutex<()>, AtomicBool, and CondVar

if you are not restricted with the standard library, I suggest:

  • parking_lot::Mutex (or maybe ReentrantMutex):
    • you can check the locked status (is this the boolean flag you wanted?) using is_locked() method, which is not possible in the standard library
    • use try_lock_for() to block calling thread with a timeout
  • event_listener::Event
    • you can check is_notified()
    • to block on it, you first get a EventListener by calling listen() method.

EDIT: I should mention, although a Mutex can be used as an event in special use cases, it's not what it is meant to. for one, at most one thread can be granted at a time; and also, "notifying" a blocking thread by "unlocking" a mutex is very cumbersome; and most importantly, Mutex is not meant to be held for long period.

3 Likes