from multiprocessing import Process #用multiprocessing可以在主進程中創建子進程
import os #導入os模塊
def mk_pro(name):
print('子進程{},id是{}'.format(name,os.getpid())) #os.getpid():查看進程id
if __name__ == '__main__':
print('父進程id是{}'.format(os.getpid()))
p = Process(target=mk_pro,args=('test',)) #利用Process創建子進程實例,target傳入函數,args傳入函數參數
#args這裏要注意,當元祖只有一個元素的時候要加上逗號,不要掉陷阱裏面了
print('子進程啓動')
p.daemon = True#將主線程設置爲Daemon線程,它退出時,其它子線程會同時退出,不管是否執行完任務
daemon 默認會是False,爲True則是它退出時,其它子線程會同時退出,不管是否執行完任務
p.start() #啓動進程
p.join() #等待子進程結束後繼續往下運行。用於進程間同步。
print('子進程結束')
這裏需要注意的是:
#這裏的父進程指得就是我們當前程序文件,如果不加if __name__ == '__main__':
#則會報錯,因爲子進程在運行時是依賴於父進程的所有內容的,創建一個子進程的
時候該子進程就會複製當前父進程的模塊。
不加會報如下錯誤:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable
總結:
# 1. Process(target=run_proc, args=('test',)) 用於創建一個子進程,target指定子進程中任務,args給target指定的任務傳參。
# 2. start()方法啓動進程
# 3. join()方法等待子進程結束後繼續往下運行。用於進程間同步。
# 4. Process(target=run_proc, args=('test',)daemon=True)
# daemon=True #將主線程設置爲Daemon線程,它退出時,其它子線程會同時退出,不管是否執行完任務
#if __name__ == '__main__':
#這裏的父進程指得就是我們當前程序文件,如果不加if __name__ == '__main__':
#則會報錯,因爲子進程在運行時是依賴於父進程的所有內容的,創建一個子進程的時候該子進程就會複製當前父進程的模塊。