A Basic Example of Threads Synchronization in Python, python中的线程同步示例
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
2
3
4
|
|
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
2
3
4
5
6
7
8
9
10
|
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
|
and finally the code for view(movie):
1
2
3
4
5
6
7
8
9
10
11
12
|
|
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 themultiprocessingmodule to have your threads played on two different processors (which can be MUCH faster). Nicely enough the two modules have the same syntax: simply replacethreadingbymultiprocessingandThreadbyProcessin the example above and it should work. - In my original program, I also use an Event to terminate
play_videoandplay_audioat the same time: when the video playing is exited,play_videounsets that Event. Inplay_audio, this event is regularly checked, and when it is seen to be unset,play_audioexits too. - Instead of using
waitto 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
2
3
|
|
支付宝扫一扫捐赠
微信公众号: 共鸣圈
欢迎讨论,邮件: 924948$qq.com 请把$改成@
QQ群:263132197
QQ: 924948
浙公网安备 33010602011771号