Python multi-thread programming (7): Inter-thread Communication

Source: Internet
Author: User

In many cases, threads need to communicate with each other. A common situation is that the secondary thread executes a specific task for the main thread and constantly reports the progress of the execution during the execution process. The preceding Conditional Variable synchronization involves inter-thread communication (threading. Condition notify method ). A more common method is to use the threading. event object.
Threading. Event allows a thread to wait for notifications from other threads. It has a built-in flag, the initial value is false. The thread enters the waiting state through the wait () method until another thread calls the Set () method to set the built-in flag to true, event notifies all threads in the waiting state to resume running. You can also use the isset () method to query the current value of the built-in state of the envent object.

Example:

 Import Threading
Import Random
Import Time

Class Mythread (threading. Thread ):
Def _ Init __ (Self, threadname, event ):
Threading. thread._ Init __ (Self, name = threadname)
Self. threadevent = event

Def Run (Self ):
Print " % S is ready " % Self. Name
Self. threadevent. Wait ()
Print " % S run! " % Self. Name

Sinal = threading. Event ()
For I In Range (10 ):
T = mythread (STR (I), Sinal)
T. Start ()

Sinal. Set ()

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.