【发布时间】:2020-05-06 06:47:08
【问题描述】:
我是多线程的新手。在阅读 Mark Lutz 的“Programming Python”时,我停留在这一行
请注意,由于其简单的无限循环,至少有一个 它的线程可能不会在您可能需要使用的 Windows 上的 Ctrl-C 上死掉 任务管理器杀死运行此脚本的 python.exe 进程或 关闭此窗口即可退出
但是根据我对线程的一点了解 当主线程退出时,所有线程都会终止。那么为什么不在这段代码中呢?
# anonymous pipes and threads, not process; this version works on Windows
import os
import time
import threading
def child(pipe_out):
try:
zzz = 0
while True:
time.sleep(zzz)
msg = ('Spam %03d\n' % zzz).encode()
os.write(pipe_out, msg)
zzz = (zzz + 1) % 5
except KeyboardInterrupt:
print("Child exiting")
def parent(pipe_in):
try:
while True:
line = os.read(pipe_in, 32)
print('Parent %d got [%s] at %s' % (os.getpid(), line, time.time()))
except KeyboardInterrupt:
print('Parent Exiting')
pipe_in, pipe_out = os.pipe()
threading.Thread(target=child, args=(pipe_out, )).start()
parent(pipe_in)
print("main thread exiting")
【问题讨论】:
-
"所有线程在主线程退出时终止" 你从哪里得到这个假设?
-
如果我错了请纠正我
-
不,我问的是你是否根据你阅读的内容建立了你的假设,但这可能是你问题的答案,他们没有。
标签: python multithreading