1. 程式人生 > >python 歸納 (八)_多進程_基本使用

python 歸納 (八)_多進程_基本使用

結束 out pyc 運行時 join() ava int 編輯器 pytho

# -*- coding: UTF-8 -*-
"""
測試進程使用 multiprocessing.Process

使用:
    1. 準備一個函數<fun>,子進程要執行的代碼放這裏面
         def run_proc(name,l_list)
    2. 以函數名、tuple(函數參數1,函數參數2...),創建Process 對象
         p = multiprocessing.Process(target=run_proc, args=(str(i),l) )
    3. 啟動子進程,這時主進程不會阻塞
         p.start()
    4. 想讓主進程阻塞,等待子進程完成,接上執行
         p.join()

總結:
   1.python 多進程類似java的多線程
   2.case 1 說明 執行子進程時 import <module> 會在各個子進程中重新執行
             也就是,無法通過 模塊.變量 實現進程間數據共享
   3.case2,case 3 執行子進程時,調用程序所在空間的變量,能在子進程函數中
     執行訪問,但是修改值無法傳遞到外面
             也就是,無法通過 調用子進程所在文件的變量實現進程間數據共享
   4.case4 不能這樣使用變量
   5.case5 從進程調用參數,傳入可改變對象list,也無法實現進程間數據共享

a.進程間數據共享要靠其他方式

疑問:
進程對象.join() 實現主進程等待子進程結束
如何實現 子進程2 等待 子進程1 結束

"""
import os,time
from multiprocessing import  Process
import psutil
import test_m # 測試模塊 裏面只有變量 m=1

c = "c"

def run_proc(name,l_list):
    print "Child process %s (%s) is running ..." % (name,os.getpid(),)
    print "sub process %s" % psutil.Process(os.getpid()).name()
    print "list:",l_list
    l_list[0] = "a" + name

    # case  1
    print test_m.m
    time.sleep(5)
    print "%s end" % os.getpid()
    test_m.m = 2

    # case  2
    # global c 加上報錯
    print c

    # case 3
    global d  # 不加報錯
    print d
    d = ‘dd‘

    # case 4
    print e  # pycharm編輯器裏不提示紅色,運行時報錯

d = "d"

if __name__ == ‘__main__‘:
    print  ‘main process %s.‘  % os.getpid()
    print "main process %s" % psutil.Process(os.getpid()).name()

    e = "e"
    test_m.m = 3
    l = ["l1","l2"]

    for i in  range(2):
        p = Process(target=run_proc, args=(str(i),l) )
        print ‘process will start,%s‘ % os.getpid()
        p.start()
        print ‘flag1 %d‘ % i
        p.join() # 等待進程完成
        print ‘flag2 %d‘ % i

        # case 5
        print ‘list in main:‘,l

    print "main end %s."  % os.getpid()
    # case 1
    print test_m.m

"""
Out:
main process 7008.
main process python.exe
process will start,7008
flag1 0
Child process 0 (1272) is running ...
sub process python.exe
list: [‘l1‘, ‘l2‘]
1
1272 end
c
d
Process Process-1:
.....省略
NameError: global name ‘e‘ is not defined
flag2 0
list in main: [‘l1‘, ‘l2‘]
process will start,7008
flag1 1
Child process 1 (3216) is running ...
sub process python.exe
list: [‘l1‘, ‘l2‘]
1
Process Process-2:
.....省略
NameError: global name ‘e‘ is not defined
3216 end
c
d
flag2 1
list in main: [‘l1‘, ‘l2‘]
main end 7008.
3
"""

  

python 歸納 (八)_多進程_基本使用