python multithreading event (communication between threads)

# Event is the communications between multiple threads

import threading, time

 

class Boss(threading.Thread):

 

  def run(self):

    print ( "Boss said: From now on we will have 996 friends, cheer")

    Event Set #

    print(event.isSet())

    event.set () after #event is set, the program after multiple threads in event.wait () will be activated to perform

    time.sleep(3)

    print ( "Boss: We finished the job, do not have a 996")

    print(event.isSet())

    event.set()

 

class Worker(threading.Thread):

  def run(self):

    event.wait()

    print ( "Worker: Oh mother, do ye also the 996")

    event.clear()

    event.wait()

    print("Worker:oh yeah......")

 

if __name__ == "__main__":

  event = threading.Event()

  threads = []

  for i in range(5):

    threads.append(Worker())

  threads.append(Boss())

  for t in threads:

    t.start()

 

# Run the above procedures, the following output can be obtained

Boss said: From now on we will have 996 friends, cheer

Worker: Oh mother, do ye also the 996

Worker: Oh mother, do ye also the 996

Worker: Oh mother, do ye also the 996

Worker: Oh mother, do ye also the 996

Worker: Oh mother, do ye also the 996

Boss: We finished the job, we do not have the 996

Worker:oh yeah......

Worker:oh yeah......

Worker:oh yeah......

Worker:oh yeah......

Worker:oh yeah......

 

Boss thread first to speak, and the state of the event set by set, activated in the program after event.wait

5 Work First thread in wait state, only to wait until after the event status is set behind the program will run, run after reset event and enter the wait state again.

 

 

 

    

 

  

Guess you like

Origin www.cnblogs.com/laofang/p/12120295.html