Python multithreaded Programming (eight): Using event to implement communication between threads _python

Source: Internet
Author: User

Use Threading. The event enables threads to communicate with each other before Python: Using the Threading module to implement multithreaded programming VII [using condition to implement complex synchronization] we have initially implemented the basic functions of communication between threads, but a more general approach is to use the threading . The event object. Use Threading. Event can cause a thread to wait for notification from other threads, we pass this event to the thread object, and the event defaults to a built-in flag with the initial value false. Once the thread passes through the wait () method to the waiting state until another thread calls the event's set () method to set the built-in flag to true, the event notifies all waiting states that the thread resumes running.

Copy Code code 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'll 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 operation effect is as follows:

Copy Code code as follows:

I am thread-1,i'll sleep ...
I am thread-2,i'll sleep ...
I am thread-3,i'll sleep ...
Main thread sleep 3 seconds ...
I am Thread-1, I awake ... I am Thread-2, I awake ...

I am Thread-3, I awake ...

Related Article

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.