1. 程式人生 > >python 多執行緒/程序間通訊

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