Python多进程中,一个进程开启后并没有执行,也无法终止
from multiprocessing import Processfrom multiprocessing import Queue
import time
def write(q, urls):
print("Process is writting...")
for url in urls:
q.put(url)
print("put %s to queue..." % url)
time.sleep(2)
def read(q):
print("Process is reading...")
while True:
url = q.get(True)
print("Get %s from queue" % url)
if __name__ == "__main__":
q = Queue()
# 父进程创建Queue,并传给各个子进程
w1 = Process(target=write, args=(q,["url_1", "url_2", "url_3"]))
w2 = Process(target=write, args=[q,["url_4", "url_5", "url_6"]])
r = Process(target=read, args=(q,))
w1.start()
w2.start()
r.start()
w1.join()
w2.join()
print(r.is_alive()) # True
r.terminate()
# 测试
print(r.is_alive()) # True
print(w1.is_alive()) # False
print(w2.is_alive()) # False
print("结束")
输出
Process is writting...put url_1 to queue...
put url_2 to queue...
put url_3 to queue...
Process is writting...
put url_4 to queue...
put url_5 to queue...
put url_6 to queue...
True
True
False
False
结束
从输出可以看出,进程r并没有执行read(),但是确是存活着,而且无法关闭
回答:
Process is writting...put url_1 to queue...
Process is writting...
put url_4 to queue...
Process is reading...
Get url_1 from queue
Get url_4 from queue
put url_2 to queue...
Get url_2 from queue
put url_5 to queue...
Get url_5 from queue
put url_3 to queue...
Get url_3 from queue
put url_6 to queue...
Get url_6 from queue
True
True
False
False
End
为什么我每次运行都没有问题,你的机子是咋了,有其他不正常的地方吗?
r.terminate() r.join()
print(r.is_alive()) # now False
print(w1.is_alive()) # False
print(w2.is_alive()) # False
print("End")
不过让r进程结束可以这样实现,我查了下文档,terminate是给结束信号,并不保证马上停止,主进程也不会等待r结束再向下执行,需要使用join方法让主进程等待子进程r结束后再向下执行。
以上是 Python多进程中,一个进程开启后并没有执行,也无法终止 的全部内容, 来源链接: utcz.com/p/937802.html