2

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!

dawfedora
  • 21
  • 1
  • Checkout concurrent.futures ? ThreadPoolExecutor could be an option – Kris May 23 '22 at 04:38
  • 1
    [`threading.Lock`](https://docs.python.org/3/library/threading.html#threading.Lock) is the most basic way of handling that. There are more higher-level mechanisms, for example `asyncio` and its [`Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future) mentioned above. – Amadan May 23 '22 at 04:44

1 Answers1

0

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(...).

Dennis
  • 2,249
  • 6
  • 12