python 多线程/进程间通信

创建子进程
目录:https://blog.csdn.net/qq_30923243/article/details/83505907

# coding:utf-8
from multiprocessing import Process
import os
#子进程要执行的代码
def run_proc(name):
    print('Run child process %s(%s)...' % (name, os.getpid()))

if __name__ == '__main__':
.    print('Parent process %s.' % os.getpid())
    p = Process(target = run_proc, args=('test',)) #子进程执行函数run_proc 子进程名字test 创建子进程
    print('Child process will start.')
    p.start() # 启动子进程
    p.join()  # 方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
    print('child process end')

批量创建子进程

from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(3) #pool默认大小是CPU核数
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

输出:

Parent process 43936.     #父进程
Waiting for all subprocesses done...
Run task 0 (43816)...     #开始创建3个子进程
Run task 1 (40776)...
Run task 2 (39044)...
Task 0 runs 0.43 seconds. # 子进程0结束
Run task 3 (43816)...     # 子进程3创建,当前pool内共有3个子进程
Task 1 runs 1.15 seconds. # 子进程1结束
Run task 4 (40776)...     # 子进程4创建,当前pool内共有3个子进程 
Task 3 runs 0.82 seconds. # 剩下的子进程执行结束
Task 4 runs 0.91 seconds.
Task 2 runs 2.12 seconds.
All subprocesses done.

进程间通信
进程间通信是通过Queue、Pipes等实现的。

# coding:utf-8
from multiprocessing import Process, Queue
import os, time, random

def write(q):
    for value in ['A', 'B', 'C']:
        print('put %s to queue' % value)
        q.put(value)
        time.sleep(random.random())

def read(q):
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)
if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

猜你喜欢

转载自blog.csdn.net/qq_30923243/article/details/84951768