python基礎===多進程

來源:互聯網
上載者:User

標籤:進程間   進程池   bsp   區別   執行個體   pre   tin   ESS   task   

進程線程的區別在進程,線程,協程的區別

linux或者unix有fork()函數,但是不支援win系統。

multiprocessing

multiprocessing模組是跨平台版本的多進程模組。支援win系統,用法如下:

from multiprocessing import Processimport 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‘,))    print(‘Child process will start.‘)    p.start()    p.join()    print(‘Child process end.‘)


>>>
Parent process 9860.
Child process will start.
Run child process test (9764)...
Child process end.

*該py檔案是通過cmd視窗執行,不然執行不了多進程

建立子進程時,只需要傳入一個執行函數和函數的參數,建立一個Process執行個體,用start()方法啟動,這樣建立進程比fork()還要簡單。

join()方法可以等待子進程結束後再繼續往下運行,通常用於進程間的同步。

 

Pool

如果要啟動大量的子進程,可以用進程池的方式大量建立子進程:

from multiprocessing import Poolimport os, time, randomdef 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(4)                         #允許運行多少個進程    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 10852.
waiting for all subprocesses done....
Run task 0 (9620)....
Run task 1 (10180)....
Run task 2 (8116)....
Task 2 runs 0.03 seconds.
Run task 3 (8116)....
Run task 4 (8744)....
Task 4 runs 0.42 seconds.
Task 0 runs 0.64 seconds.
Task 1 runs 1.15 seconds.
Task 3 runs 2.90 seconds.
All  subprocesses done.

 

 

 

 

 

 

參考資料:

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431927781401bb47ccf187b24c3b955157bb12c5882d000

 

python基礎===多進程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.