Python multiprocessing 多进程

在multiporcessing中,通过新建Process对象创建进程,然后用start()方法调用它。Process与threading.Thread类似。如下是一个简单的例子:

from multiprocessing import Process

def f(name):
    print('hello' ,name)

if __name__ == '__main__':
    p = Process(target=f, args('bob',))
    p.start()
    p.join()

Queues

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()

Queues是线程和进程安全的。

Pipes

Pipe可以是单向(half-duplex),也可以是双向(duplex)。我们通过mutiprocessing.Pipe(duplex=False)创建单向管道 (默认为双向)。一个进程从PIPE一端输入对象,然后被PIPE另一端的进程接收,单向管道只允许管道一端的进程输入,而双向管道则允许从两端输入。 

import multiprocessing as mul


def proc1(pipe):
    pipe.send('hello')
    print('proc1 rec:', pipe.recv())


def proc2(pipe):
    print('proc2 rec:', pipe.recv())
    pipe.send('hello, too')


# Build a pipe
pipe = mul.Pipe()
if __name__ == '__main__':
    # Pass an end of the pipe to process 1
    p1 = mul.Process(target=proc1, args=(pipe[0],))
    # Pass the other end of the pipe to process 2
    p2 = mul.Process(target=proc2, args=(pipe[1],))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
proc2 rec: hello
proc1 rec: hello, too

Pipe()函数返回一对用pipe连接在一起的对象,默认情况下是双向的。例如:

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()

使用Pipe()表示管道的两端,用来连接两个对象。每个连接的对象有send()和recv()方法。注意,如果两个进程(或线程)尝试在同一时间往pipe的一端读取或写入,在pipe中的数据会出现问题。当然,在同一时间使用不同pipe的不同的端就不回出现问题。

参考:

https://www.cnblogs.com/gmhappy/p/11863960.html

https://hiteshmishra708.medium.com/multiprocessing-in-python-c6735fa70f3f

Python多进程并行操作-multiprocessing简单使用 - 知乎 

猜你喜欢

转载自blog.csdn.net/linzhiji/article/details/131577850