扔了 python 的多线程吧。试试 asyncio 或者 greenlet 协程。
协程的好处是它的中断都是可控的,我写两个版本给你看看:
gevent 版本:
from gevent import spawn_later, sleep
def do_something():
i = 1
while True:
print("counting:", i)
i += 1
sleep(1)
g = spawn_later(0, do_something)
sleep(3)
g.kill()
g.join()
标准库 asyncio 版本:
from asyncio import sleep, get_event_loop, ensure_future, wait
async def do_something():
i = 1
while True:
print("counting:", i)
i += 1
await sleep(1)
async def main():
c = ensure_future(do_something(), loop=loop)
await sleep(3)
c.cancel()
# for python 3.6
loop = get_event_loop()
loop.run_until_complete(main())
loop.close()
# for python 3.7+
# from asyncio import run
# run(main)
【 在 giantman (捷安特·建特·脑白金) 的大作中提到: 】
: 我觉得您没有理解我的意思。
: 我当然知道打印一个“the end”并不是就结束了,实际上,最后一句print("the end")无关紧要。
: 我的意思是:按照书上的说法,setDaemon为True时,子线程应该与主线程同时结束,但我实际运行的结果不是这样,无论setDameno设置为True还是False,子线程都不与主线程同时结束,还是在主线程结束后继续运行子线程。
: ...................
--
修改:hgoldfish FROM 125.78.66.*
FROM 125.78.66.*