python 進程、線程

python中進程、線程相關的知識點總結;
mac和windows中略有區別,使用函數並不一樣,因爲兩個操作系統的內核不同。
一、進程
三點:1.創建子進程;2.創建多個子進程;3.進程通信
官網參考文檔:doc
1
mac系統引入os模塊,使用函數fork;win系統引入process模塊,使用Process類創建新的進程;
獲取進程id使用os.getpid即可獲取當前進程號

import random
from multiprocessing import Process
from multiprocessing import Pool
import os
import time


def test(arg='name'):
    print('test name: ' + arg + ', pid: ' + str(os.getpid()))
    start = time.time()
    time.sleep(random.random())
    end = time.time()
    print('cost %.2f' %(end - start))


def test_process():
    p = Process(target=test, args=('New process!',))
    print('Start other process')
    p.start()
    p.join()  # 可以等待子進程結束後再繼續往下運行,通常用於進程間的同步


if __name__ == '__main__':
    test_process()
    print('main Process is: ' + str(os.getpid()))

2

3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章