http://zulko.github.io/blog/2013/09/19/a-basic-example-of-threads-synchronization-in-python/
We will see how to use threading Events to have functions in different Python threads start at the same time.
I recently coded a method to view movies in Python : it plays the video, and in the same time, in a parralel thread, it renders the audio. The difficult part is that the audio and video should be exactly synchronized. The pseudo-code looks like this:
1 |
|
In this code, play_audio()
and play_video()
will start at approximately the same time and will run parallely, but these functions need some preparation before actually starting playing stuff. Their code looks like that:
1 |
|
To have a well-synchronized movie we need the internal functions audio.start_playing()
and video.start_playing()
, which are run in two separate threads, to start at exactly the same time. How do we do that ?
The solution seems to be using threading.Event
objects. An Event
is an object that can be accessed from all the threads and allows very basic communication between them : each thread can set or unset an Event, or check whether this event has already been been set (by another thread).
For our problem we will use two events video_ready
and audio_ready
which will enable our two threads to scream at each other “I am ready ! Are you ?”. Here is the Python fot that:
1 |
|
and finally the code for view(movie)
:
1 |
|
A few tips tips to go further:
- Here I am using the module
threading
, and the two threads will be played in parrallel on the same processor. If you have a computer with several processors you can also use themultiprocessing
module to have your threads played on two different processors (which can be MUCH faster). Nicely enough the two modules have the same syntax: simply replacethreading
bymultiprocessing
andThread
byProcess
in the example above and it should work. - In my original program, I also use an Event to terminate
play_video
andplay_audio
at the same time: when the video playing is exited,play_video
unsets that Event. Inplay_audio
, this event is regularly checked, and when it is seen to be unset,play_audio
exits too. - Instead of using
wait
to wait for an Event to be set, you can use a loop to you decide at which frequency you want to check the Event. Only do that if don’t mind a lag of a few milliseconds between your processes :
1 |
|