zoukankan      html  css  js  c++  java
  • day32-1 事件Event

    事件Event-线程

    每一个线程都是独立运行且状态不可预测。你把一个任务丢到子线程中,这个任务将异步执行,如何获取到这个任务的执行状态?使用threading库中的Event对象。对象包含一个可由线程设置的信号标志,线程直到等到该标志为真时再启动执行

    event.isSet() # 返回event的状态值
    event.is_set()  # 返回event的状态值
    event.wait()  # 等待event状态值为True
    event.set()  # 设置event的状态值为True,所有阻塞的线程激活进入就绪状态,等待操作系统调度
    event.clear()  # 恢复event的状态值为False
    

    假设:一个线程负责启动服务器,启动服务器需要花一定的时间;另一个线程作为客户端,要连接服务器必须保证服务器已经启动。

    import time
    from threading import Thread, Event
    
    
    def connect_server():
        print('server ready ro started!')
        time.sleep(2)
        print('server starting....')
        event.set()  # 事件标志设为True
    
    
    def connect_client():
        print('wait server start....')
        event.wait()  # 等待服务端启动,事件标识为True
        print('client starting')
        event.clear()  
    
        
    event = Event()
    server = Thread(target=connect_server)
    client = Thread(target=connect_client)
    server.start()
    client.start()
    
  • 相关阅读:
    ajax post 数组
    Hello 2018 ABC
    A. The Way to Home
    Codeforces Round #453 (Div. 2) ABC
    Codeforces Round #452 (Div. 2) D
    Codeforces Round #452 (Div. 2) ABC
    Python 常用技巧
    Codeforces Round #451 (Div. 2) E
    Codeforces Round #451 (Div. 2) D. Alarm Clock
    Codeforces Round #451 (Div. 2) ABC
  • 原文地址:https://www.cnblogs.com/863652104kai/p/11146077.html
Copyright © 2011-2022 走看看