python 進程,python

來源:互聯網
上載者:User

python 進程,python

參考部落格:https://www.cnblogs.com/vamei/archive/2012/10/12/2721484.html

一、前言

  Python的線程或進程都是叫用作業系統的原生線程或進程,但是由於GIL的存在,python多線程並不能利用cpu多核的優勢。而python的進程是不存在GIL的,各個進程間的資料是獨立的安全的,所有python多進程可以利用多核優勢。

  各自適用情況:

  python多線程: I/O 操作密集型任務

  python多進程: CPU密集型任務

二、multiprocessing  
multiprocessing is a package that supports spawning processes using an API similar to the threading module.The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.multiprocessing包是Python中的多流程管理組件,用類似於線程模組的API來建立進程(multiprocessing的很大一部份與threading使用同一套API,只不過換到了多進程的情境)。多流程管理組件提供本地和遠端並發,通過使用子進程而不是線程有效避開了GIL由於這個原因,multiprocessing允許程式員充分利用給定機器上的多個處理器。它可以在Unix和Windows上運行。

  與threading.Thread類似,它可以利用multiprocessing.Process對象來建立一個進程。該進程可以運行在Python程式內部編寫的函數。該Process對象與Thread對象的用法相同,也有start(), run(), join()的方法。此外multiprocessing包中也有Lock/Event/Semaphore/Condition類

但在使用這些共用API的時候,我們要注意以下幾點:

  • 在UNIX平台上,當某個進程終結之後,該進程需要被其父進程調用wait,否則進程成為殭屍進程(Zombie)。所以,有必要對每個Process對象調用join()方法 (實際上等同於wait)。對於多線程來說,由於只有一個進程,所以不存在此必要性。
  • multiprocessing提供了threading包中沒有的IPC(比如Pipe和Queue),效率上更高。應優先考慮Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (因為它們佔據的不是使用者進程的資源)。
  • 多進程應該避免共用資源。在多線程中,我們可以比較容易地共用資源,比如使用全域變數或者傳遞參數。在多進程情況下,由於每個進程有自己獨立的記憶體空間,以上方法並不合適。此時我們可以通過共用記憶體和Manager的方法來共用資源。但這樣做提高了程式的複雜度,並因為同步的需要而降低了程式的效率。

Process.PID中儲存有PID,如果進程還沒有start(),則PID為None。

三、案例  3.1 定義進程
import multiprocessing  import timeimport osdef run(name):    time.sleep(2)    print('hello', name)if __name__ == '__main__':    start_time = time.time()    p_list = []    for i in range(10):        p = multiprocessing.Process(target=run, args=('bob%s' % i,))  # 建立一個進程對象        p.start()        print(p.name, p.pid)   # 進程名 和 pid        p_list.append(p)        # p.join()     # 和線程一樣,join會阻塞    for p in p_list:        p.join()    print('parent process', os.getppid())    print('total time', time.time()-start_time)
  3.2 進程中嵌入線程
# -*- coding: UTF-8 -*-import multiprocessingimport timeimport osimport threadingdef threading_run(name):    print('name:', name)def run(name):    time.sleep(2)    t = threading.Thread(target=threading_run, args=(name,))  # 定義線程    t.start()    # print('hello', name)if __name__ == '__main__':    start_time = time.time()    for i in range(10):        p = multiprocessing.Process(target=run, args=('bob%s' % i,))  # 進程        p.start()        # print(p.name, p.pid)    print('parent process', os.getppid())

  註:和線程一樣,主進程也預設不會等待子進程結束

  3.3 父進程和子進程

  

from multiprocessing import Processimport osdef info(title):    print(title)    print('module name:', __name__)    print('parent process:', os.getppid())    print('process id:', os.getpid())    print("\n\n")def f(name):    info('\033[31;1mfunction f\033[0m')    print('hello', name)if __name__ == '__main__':    info('\033[32;1mmain process line\033[0m')    p = Process(target=f, args=('bob',))    p.start()    p.join()

  結果:

main process linemodule name: __main__parent process: 2464process id: 13628function fmodule name: __mp_main__parent process: 13628process id: 17480hello bob

  註:

    parent process: 2464  是我電腦中PyCharm 的進程號

    process id: 13628    是  主進程('__main__')的進程號

    process id: 17480    是  子進程 p 的進程號

    所以可以看出,所有的進程都是由父進程啟動的

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.