1.target指定目標函數(shù)來初始化進程
import multiprocessing
import time
def worker(interval):
n = 5
while n > 0:
print("The time is {0}".format(time.ctime()))
time.sleep(interval)
n -= 1
if __name__ == "__main__":
p = multiprocessing.Process(target=worker, args=(3,))
p.start()
print("p.pid:", p.pid)
print("p.name:", p.name)
print("p.is_alive:", p.is_alive())
2. 重寫Process類來初始化線程
import multiprocessing
import time
import os
lock = multiprocessing.Lock()
s = multiprocessing.Semaphore(2)
class ClockProcess(multiprocessing.Process):
def __init__(self, interval):
multiprocessing.Process.__init__(self)
self.interval = interval
def run(self):
s.acquire()
lock.acquire()
n = 5
while n > 0:
print("the time is {0}".format(time.ctime()))
time.sleep(self.interval)
n -= 1
lock.release()
s.release()
if __name__ == '__main__':
# lock = multiprocessing.RLock()
p = ClockProcess(3)
p.daemon = True
p.start()
time.sleep(7)
os.kill(p.pid,9)
p.join()
3.RuntimeError
# RuntimeError:
# Attempt to start a new process before the current process
# has finished its bootstrapping phase.
#
# This probably means that you are on Windows 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 a Windows executable.
原因
由于Python運行過程中独泞,新創(chuàng)建進程后,進程會導入正在運行的文件比驻,即在運行代碼的時候,代碼在運行到mp.Process時,新的進程會重新讀入該代碼阳堕,對于沒有if name=="main"保護的代碼松忍,新進程都認為是要再次運行的代碼蒸殿, 這是子進程又一次運行mp.Process,但是在multiprocessing.Process的源碼中是對子進程再次產(chǎn)生子進程是做了限制的鸣峭, 是不允許的宏所,于是出現(xiàn)如上的錯誤提示。
解決方法
- 多進程一般在if__name__=="main"模塊下調(diào)用
在Python有關(guān)main的文檔中 【2】 說明“main”是代碼執(zhí)行時的最高的命名空間(the name of the scope in which top-level code executes)摊溶,當代碼被當做腳本讀入的時候爬骤,命名空間會被命名為“main”,對于在腳本運行過程中讀入的代碼命名空間都不會被命名為“main”莫换。 這也就是說創(chuàng)建的子進程是不會讀取name=="main"保護下的代碼霞玄。