Are you using RPi.GPIO library
? Or you call your Python code from C when a callback fires?
In case of RPi.GPIO
, it runs a valid Python thread, and you do not need extra synchronization if you organize the threads interaction properly.
The most common pattern is to put your event in a queue (in case of Python 3 this library will do the job, Python 2 has this one). Then, when your main thread is ready to process the event, process all the events in your queue. The only problem is how you find a moment for processing them. The simplest solution is to implement a function that does that and call it from time to time. If you use a long sleep
call, you may have to split it into many smaller sleeps to make sure the external events are processed often enough. You may even implement your own wrapper for sleep
that splits one large delay into several smaller ones and processes the queue between them. The other solution is to use Queue.get
with timeout
parameter instead of sleep
(it returns immediately after an event arrives into the queue), however, if you need to sleep exactly for a period you specified, you may have to do some extra magic such as measuring the time yourself and calling get
again if you need to wait more after processing the events.