Python多进程同步Lock、Semaphore、Event实例

同步的方法基本与多线程相同。

1) Lock

当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。

import multiprocessing

import sys

def worker_with(lock, f):

    with lock:

        fs = open(f,"a+")

        fs.write('Lock acquired via with\n')

        fs.close()

       

def worker_no_with(lock, f):

    lock.acquire()

    try:

        fs = open(f,"a+")

        fs.write('Lock acquired directly\n')

        fs.close()

    finally:

        lock.release()

if __name__ == "__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()

以上是 Python多进程同步Lock、Semaphore、Event实例 的全部内容, 来源链接: utcz.com/z/315512.html

回到顶部