Python多進程編程-進程生命週期管理

主要函數:
Process():創建進程實例
start():啓動進程
join():主進程阻塞,等待子進程執行結束
terminate():強行終止,不推薦
exitcode():進程執行的返回值
is_alive() :判斷進程是否正在運行

實例代碼:

import multiprocessing
import time
def func1(msg):
    for i in xrange(5):
        time.sleep(2)
        print msg,i
if __name__ == '__main__':
    p1=multiprocessing.Process(target=func1,args=('hello world!',))
    print p1.is_alive()
    p1.start()
    print p1.is_alive()
    p1.join()
    print p1.exitcode
    print 'main........'#因爲線程調用了join,使主進程阻塞,等待子進程(func1函數)執行完。所以最後打印'main.....'

執行結果:

False
True
hello world! 0
hello world! 1
hello world! 2
hello world! 3
hello world! 4
0
main........
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章