python基于event实现线程间通信控制

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python基于event实现线程间通信控制

  2021-04-02 我要评论

这篇文章主要介绍了python基于event实现线程间通信控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

import threading,time
class Boss(threading.Thread):
  def run(self):
    print("We must work today!")
    event.isSet() or event.set()
    time.sleep(5)
    print("You can go home right now!")
    event.isSet() or event.set()

class Worker(threading.Thread):
  def run(self):
    event.wait()
    print("Oh,my god!!!")
    time.sleep(1)
    event.clear()
    event.wait()
    print("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()
  for t in threads:
    t.join()

运行后显示:

We must work today!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
Oh,my god!!!
You can go home right now!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!
Oh,yeah!!!

Process finished with exit code 0
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们