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")
    
  • 相关阅读:
    JavaScript 之 typeof
    Octotree Chrome安装与使用方法
    支持主流MySQL中间件的数据迁移工具ora2mysql
    Eclipse搭建SpringBoot之HelloWorld
    Spring Boot插件spring tool suite安装及使用
    树的前中后序遍历非递归实现
    判断是否是完全二叉树
    Leetcode 437_path sum III todo
    DFS回溯只在递归基回溯————leetcode112
    Leetcode 94 Binary Tree Inorder
  • 原文地址:https://www.cnblogs.com/zhouzetian/p/12641908.html
Copyright © 2011-2022 走看看