zoukankan      html  css  js  c++  java
  • Python多进程同步Lock、Semaphore、Event的使用

    """Python多进程同步Lock、Semaphore、Event实例,Lock用来避免访问冲突、Semaphore用来控制对共享资源的访问数量、Event用来实现进程间同步通信,"""
    # Lock: 当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突
    import multiprocessing
    import time
    import sys
    
    
    def worker_with(lock, f):
        with lock:
            fs = open(f, "a+")
            fs.write('Lock acquired via with
    ')
            fs.close()
    
    
    def worker_no_with(lock, f):
        lock.acquire()
        try:
            fs = open(f, "a+")
            fs.write('Lock acquired directly
    ')
            fs.close()
        finally:
            lock.release()
    
    
    def main():
        f = "file.txt"
    
        lock = multiprocessing.Lock()
        w = multiprocessing.Process(target=worker_with, args=(lock, f))
        nw = multiprocessing.Process(target=worker_no_with, args=(lock, f))
    
        w.start()
        nw.start()
    
        w.join()
        nw.join()
    
    
    
    # Semaphore用来控制对共享资源的访问数量,例如池的最大连接数
    def worker(s, i):
        s.acquire()
        print(multiprocessing.current_process().name + "acquire")
        time.sleep(i)
        print(multiprocessing.current_process().name + "release")
        s.release()
    
    def main1():
        # 使用sempaphore限制了最多有2个进程同时执行
        s = multiprocessing.Semaphore(2)
        for i in range(5):
            p = multiprocessing.Process(target=worker, args=(s, i*2))
            p.start()
    
    
    # Event用来实现进程间同步通信
    def wait_for_event(e):
        print('wait_for_event: starting')
        e.wait()
        print('wait_for_event: e.is_set()->' + str(e.is_set()))
    
    def wait_for_event_timeout(e, t):
        print('wait_for_event_timeout: starting')
        e.wait(t)
        print('wait_for_event_timeout: e.is_set()->' + str(e.is_set()))
    
    def main2():
        e = multiprocessing.Event()
        w1 = multiprocessing.Process(target=wait_for_event, args=(e,))
        w1.start()
        w2 = multiprocessing.Process(target=wait_for_event_timeout, args=(e, 2))
        w2.start()
        time.sleep(3)
        e.set()
        print("main: event is set")
    
  • 相关阅读:
    弹飞绵羊
    POJ 3308
    狼抓兔子
    块状链表题*1
    块状链表
    双向链表
    Linux入职基础-1.2_U盘安装RedHat5具体步骤
    Linux入职基础-1.1_国内开源的主要镜像站
    VS.NET(C#)--2.9_HTML服务器控件案例
    VS2015按钮方法
  • 原文地址:https://www.cnblogs.com/zhouzetian/p/12641908.html
Copyright © 2011-2022 走看看