標籤:分區 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多進程