'In Python, Best way to sleep awaiting a callback

I am writing some python wrappers for a c++ library that speaks to a hardware device. The general model of the library is to register a callback routine, then send a command to the hardware and await the callback.

I could simply loop checking a variable which gets set by the callback routine, but that feels stupid, as the program calling the wrappers may some day like to do other stuff while waiting. So I would rather sleep on a semaphore and have the callback do a wakeup on the semaphore so that we can get all multi-threaded in the future.

Is that a thing in Python? I am new to Python, but have experience with multi-threaded c and c++ device drivers. I would like pointers to a clean way to do this in Python 3.

Thanks!



Solution 1:[1]

Using an atomic message queue like queue.Queue() is nice because if you call .get(...) on it while it is empty, it will automatically wait on a semaphore until someone (like your callback function) calls .put(...).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1