[b0041] python 归纳 (二六)_多进程数据共享和同步_事件Event

# -*- coding: utf-8 -*-
"""
多进程 同步  事件multiprocessing.Event

逻辑:
    子线程负责打印,会阻塞, 等待主进程发出控制信号 以便继续

总结:
    个人理解, multiprocessing.Event 中维护了一个boolean变量,初始值为Fasle
    e.wait() 如果为Fasle会阻塞,True继续执行 ,
    set() 将值设置为True
    clear()  将值设置为False
    is_set() 查看

    不确定是否支持多个子进程同时e.wait()阻塞中,然后主进程 set()后 全部唤醒

使用:
    1. 创建事件对象 e = multiprocessing.Event()
    2. e传给子进程,在进程中 e.wait([secondes]) 阻塞
    3. 在另外的进程中  e.set() 通知阻塞的进程不要阻塞了
    4. 必要时 e.clear() 恢复初始值

"""
import multiprocessing
import time

# case1
def wait_for_event(e):
    print("wait_for_event: starting")

    # 一直等到e.set()在某个进程中执行
    e.wait()

    print("wairt_for_event: e.is_set()->" + str(e.is_set()))

# case2
def wait_for_event_timeout(e, t):
    print("wait_for_event_timeout:starting")

    # 等到e.set()在某个进程中执行 或者时间t到了
    e.wait(t)

    print("wait_for_event_timeout:e.is_set->" + str(e.is_set()))

if __name__ == "__main__":

    # 创建事件对象,初始值 无效
    e = multiprocessing.Event()

    ## case 1 一直等待
    multiprocessing.Process(name="block", target=wait_for_event, args=(e,)).start()

    time.sleep(3)

    print "set"
    e.set()           # 设置事件有效,此时执行e.wait()的子进程接触阻塞
    print e.is_set()  # 查看事件是否有效

    time.sleep(0.1)
    print "clear"
    e.clear()         # 设置事件无效
    print e.is_set()

    ## case 2 最多等待2秒
    print "------case2"
    multiprocessing.Process(name="non-block", target=wait_for_event_timeout, args=(e, 2)).start()

    time.sleep(3)

    print "end"
    print e.is_set()

"""
Out:
wait_for_event: starting
set
True
wairt_for_event: e.is_set()->True
clear
False
------case2
wait_for_event_timeout:starting
wait_for_event_timeout:e.is_set->False
end
False
"""

 

posted @ 2018-09-12 23:00  sunzebo  阅读(444)  评论(0编辑  收藏  举报