python并发——进程间同步和通信

一.进程间同步

对于一些临界资源,不能使用并发无限消耗,就需要设置专门的临界标示,比如锁或者信号量等

from multiprocessing import Process, Lock
import time

def f(l, i):
    l.acquire()
    try:
        print('hello world', i)
        time.sleep(1)
    finally:
        l.release()
def f2(l, i):
    l.acquire()
    try:
        print('nin hao?', i)
        time.sleep(1)
    finally:
        l.release()

if __name__ == '__main__':
    lock = Lock()

    for num in range(10):
        Process(target=f, args=(lock, num)).start()
        Process(target=f2, args=(lock, num)).start()

二.进程间通信

有时候需要在进程之间交换对象

multiprocessing 支持进程之间的两种通信通道:

(1).队列

Queue 类是一个近似 queue.Queue 的克隆。 例如:

from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())    # prints "[42, None, 'hello']"
    p.join()

队列是线程和进程安全的。

(2).管道

Piep 函数返回一个由管道连接的连接对象,默认情况下是双工(双向)。例如:

from multiprocessing import Process, Pipe

def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "[42, None, 'hello']"
    p.join()
原文地址:https://www.cnblogs.com/wangbin2188/p/11936996.html