1. 程式人生 > 實用技巧 >Python多工-程序的原理與實現,這裡有最全面的詳解,看這篇文章就夠了

Python多工-程序的原理與實現,這裡有最全面的詳解,看這篇文章就夠了

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理

本篇文章來自騰訊雲 作者:孤獨的明月

( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載!還有海量最新2020python學習資料。 )

程序的建立-multiprocessing

multiprocessing模組就是跨平臺版本的多程序模組,提供了一個Process類來代表一個程序物件,這個物件可以理解為是一個獨立的程序,可以執行另外的事情

# -*- coding:utf-8 -*-
from multiprocessing import Process import time def run_proc(): """子程序要執行的程式碼""" while True: print("----2----") time.sleep(1) if __name__=='__main__': p = Process(target=run_proc) p.start() while True: print("----1----") time.sleep(1)

建立子程序時,只需要傳入一個執行函式和函式的引數,建立一個Process例項,用start()方法啟動

程序pid

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time

def run_proc():
    """子程序要執行的程式碼"""
    print('子程序執行中,pid=%d...' % os.getpid())  # os.getpid獲取當前程序的程序號
    print('子程序將要結束...')

if __name__ == '__main__':
    print('父程序pid: %d' % os.getpid())  # os.getpid獲取當前程序的程序號
p = Process(target=run_proc) p.start()

給子程序指定的函式傳遞引數

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
from time import sleep


def run_proc(name, age, **kwargs):
    for i in range(10):
        print('子程序執行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid()))
        print(kwargs)
        sleep(0.2)

if __name__=='__main__':
    p = Process(target=run_proc, args=('test',18), kwargs={"m":20})
    p.start()
    sleep(1)  # 1秒中之後,立即結束子程序
    p.terminate()
    p.join()
執行結果:

子程序執行中,name= test,age=18 ,pid=45097...
{'m': 20}
子程序執行中,name= test,age=18 ,pid=45097...
{'m': 20}
子程序執行中,name= test,age=18 ,pid=45097...
{'m': 20}
子程序執行中,name= test,age=18 ,pid=45097...
{'m': 20}
子程序執行中,name= test,age=18 ,pid=45097...
{'m': 20}

程序間不同享全域性變數

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time

nums = [11, 22]

def work1():
    """子程序要執行的程式碼"""
    print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
    for i in range(3):
        nums.append(i)
        time.sleep(1)
        print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))

def work2():
    """子程序要執行的程式碼"""
    print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))

if __name__ == '__main__':
    p1 = Process(target=work1)
    p1.start()
    p1.join()

    p2 = Process(target=work2)
    p2.start()
執行結果:

in process1 pid=11349 ,nums=[11, 22]
in process1 pid=11349 ,nums=[11, 22, 0]
in process1 pid=11349 ,nums=[11, 22, 0, 1]
in process1 pid=11349 ,nums=[11, 22, 0, 1, 2]
in process2 pid=11350 ,nums=[11, 22]

程序間通訊-Queue

可以使用multiprocessing模組的Queue實現多程序之間的資料傳遞,Queue本身是一個訊息列隊程式。

我們以Queue為例,在父程序中建立兩個子程序,一個往Queue裡寫資料,一個從Queue裡讀資料:

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:
        if not q.empty():
            value = q.get(True)
            print('Get %s from queue.' % value)
            time.sleep(random.random())
        else:
            break

if __name__=='__main__':
    # 父程序建立Queue,並傳給各個子程序:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 啟動子程序pw,寫入:
    pw.start()    
    # 等待pw結束:
    pw.join()
    # 啟動子程序pr,讀取:
    pr.start()
    pr.join()
    # pr程序裡是死迴圈,無法等待其結束,只能強行終止:
    print('')
    print('所有資料都寫入並且讀完')

"""
輸入如下:
Put A to queue...
Put B to queue...
Put C to queue...
Get A from queue.
Get B from queue.
Get C from queue.

所有資料都寫入並且讀完
"""