Python多進程

來源:互聯網
上載者:User

標籤:分區   roc   int   com   運行   添加   win   rgs   start   

用win api寫程式的時候,多進程的程式基本沒寫過,因為多線程已經能夠滿足大部分需要。

但是python的多線程有個問題,進程內的線程都是共用一個CPU核心的,類似於單線程的時間分區。以前寫的時候記得這個問題處理起來難度還挺大,後來就沒再搞了。

 1 from multiprocessing import Process 2 import os 3  4 def run_proc (name): 5     print ‘Run child process is %s, pid = %d‘ % ( name, os.getpid() ) 6  7 if __name__ == ‘__main__‘: 8     print ‘Run Parent process pid is = %d‘ % os.getpid() 9     SecondProcess = Process ( target = run_proc, args = (‘test‘, ) )10     print ‘starting Second process‘11     SecondProcess.start()12     print ‘Child process end‘

參照廖雪峰上教程寫的一個多進程程式,能同時運行2個進程,然後退出。

 1 from multiprocessing import Process 2 import os 3  4 def run_proc (name): 5     print ‘Run child process is %s, pid = %d‘ % ( name, os.getpid() ) 6     val = 0; 7     while 1: 8         val += 1 9 10 if __name__ == ‘__main__‘:11     print ‘Run Parent process pid is = %d‘ % os.getpid()12     SecondProcess = Process ( target = run_proc, args = (‘test‘, ) )13     print ‘starting Second process‘14     SecondProcess.start()15     val = 0;16     while 1:17         val += 118     print ‘Child process end‘

然後在兩個進程檔案中添加死迴圈的代碼,看下CPU的使用方式:

可以看到,同時啟動並執行2個線程是分佔處理器的,能夠充分發揮硬體的效能。

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.