Python multi-thread programming (8): Use Event to implement inter-thread communication

Source: Internet
Author: User
This article mainly introduces Python multi-thread programming (8): Use Event to implement inter-thread communication. if you need it, refer to threading. event can implement inter-thread communication. The previous Python: Use the threading module to implement multi-thread programming. 7. [use Condition to implement complex synchronization] we have initially implemented the basic functions of inter-thread communication, however, a more general approach is to use threading. event object. With threading. Event, a thread can wait for notifications from other threads. we pass this Event to the thread object. by default, the Event has a built-in flag with the initial value of False. Once the thread enters the waiting state through the wait () method, until another thread calls the set () method of the Event to set the built-in flag to True, this Event will notify all threads in the waiting state to resume running.

The code is as follows:


'''
Created on 2012-9-9

@ Author: walfred
@ Module: thread. TreadTest8
'''

Import threading
Import time

Class MyThread (threading. Thread ):
Def _ init _ (self, signal ):
Threading. Thread. _ init _ (self)
Self. singal = signal

Def run (self ):
Print "I am % s, I will sleep..." % self. name
Self. singal. wait ()
Print "I am % s, I awake..." % self. name

If _ name _ = "_ main __":
Singal = threading. Event ()
For t in range (0, 3 ):
Thread = MyThread (singal)
Thread. start ()

Print "main thread sleep 3 seconds ..."
Time. sleep (3)

Singal. set ()

The running effect is as follows:

The code is as follows:


I am Thread-1, I will sleep...
I am Thread-2, I will sleep...
I am Thread-3, I will sleep...
Main thread sleep 3 seconds...
I am Thread-1, I awake... I am Thread-2, I awake...

I am Thread-3, I awake...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.