Python thread Event

Source: Internet
Author: User

The events of the Python thread are used for the main thread to control the execution of other threads, and the event provides three methods wait, clear, set

Event handling mechanism: A global definition of a "flag", if the "flag" value is False, then when the program executes the Event.wait method is blocked, if the "flag" value is true, then the Event.wait method will no longer block.

    • Clear: Set "Flag" to False
    • Set: Sets "Flag" to True

With threading. Event implements inter-thread communication
Use Threading. Event allows a thread to wait for notifications from other threads, and we pass this event to the thread object,
Event has a flag built in by default and the initial value is false.
Once the thread enters the wait state through the Wait () method, until another thread calls the event's set () method to set the built-in flag to true,
The event notifies all waiting-state threads to resume running.

import Threading Import Time Class MyThread ( Threading. Thread): Def __init__ (self, Signal): Threading. Thread.__init__ (self) # initialize Self.singal = Signal def run (self): print "I am%s,i             Would sleep ... "%self.name # into the waiting state self.singal.wait () print" I am%s, I awake ... "%self.name if __name__ = = "__main__": # initial is False Singal = threading. Event () for T in range (0, 3): thread = MyThread (Singal) Thread.Start () print "main thre Ad Sleep 3 seconds ... "Time.sleep (3) # wake-up thread with signal, waiting state singal.set ()  
Import Threading  def Do (event):    print ' Start '    event.wait ()    print ' execute '  event_obj = threading . Event () for I in range:    t = Threading. Thread (Target=do, args= (Event_obj,))    T.start () event_obj.clear () # continues to block INP = raw_input (' input: ') if InP = = ' true ':    Event_obj.set () #唤醒

  

  

Python thread Event

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.