The specific operation scheme of Event in Python Library

Source: Internet
Author: User

The Python Library computer language is widely used in practical applications, and few people will involve the specific application of the Event specific operation solution in the Python Library, the following is a detailed description of the relevant steps in actual operations.

This corresponds to. NET ManualResetEvent and is used for collaborative operations among multiple threads. Event. wait () waits for the Event signal to continue execution. set () sets the signal so that the waiting thread can execute and clear () clears the signal.

 
 
  1. event1 = Event()  
  2. event2 = Event()  
  3. def test1():  
  4. for i in range(5):  
  5. event1.wait()   

WAITING SIGNAL

 
 
  1. print currentThread().name, i  
  2. event1.clear()  

After the command is executed, clear the flag so that you need to wait for the notification again at the next wait.

 
 
  1. event2.set()  

Set another wait event to send signals to another thread.

 
 
  1. def test2():  
  2. for i in range(5):  
  3. event2.wait()  
  4. print currentThread().name, i  
  5. event2.clear()  
  6. event1.set()  
  7. Thread(target = test1).start()  
  8. Thread(target = test2).start()  
  9. event1.set()   

Remember to activate one first, otherwise it will all be "waiting for death. Output:

 
 
  1. $ ./main.py  
  2. Thread-1 0  
  3. Thread-2 0  
  4. Thread-1 1  
  5. Thread-2 1  
  6. Thread-1 2  
  7. Thread-2 2  
  8. Thread-1 3  
  9. Thread-2 3  
  10. Thread-1 4  
  11. Thread-2 4  

The above article introduces the actual operation scheme of Event in Python Library.

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.