我无法弄清楚的是,尽管ThreadPoolExecutor使用守护进程工作者,即使主线程退出,它们仍然会运行.
我可以在python3.6.4中提供一个最小的例子:
import concurrent.futures
import time
def fn():
while True:
time.sleep(5)
print("Hello")
thread_pool = concurrent.futures.ThreadPoolExecutor()
thread_pool.submit(fn)
while True:
time.sleep(1)
print("Wow")
Run Code Online (Sandbox Code Playgroud)
主线程和工作线程都是无限循环.所以如果我KeyboardInterrupt用来终止主线程,我希望整个程序也会终止.但实际上工作线程仍在运行,即使它是一个守护程序线程.
ThreadPoolExecutor确认工作线程是守护程序线程的源代码:
t = threading.Thread(target=_worker,
args=(weakref.ref(self, weakref_cb),
self._work_queue))
t.daemon = True
t.start()
self._threads.add(t)
Run Code Online (Sandbox Code Playgroud)
此外,如果我手动创建一个守护程序线程,它就像一个魅力:
from threading import Thread
import time
def fn():
while True:
time.sleep(5)
print("Hello")
thread = Thread(target=fn)
thread.daemon = True
thread.start()
while True:
time.sleep(1)
print("Wow")
Run Code Online (Sandbox Code Playgroud)
所以我真的无法弄清楚这种奇怪的行为.
来自doc:https: //docs.python.org/3/library/asyncio-stream.html#asyncio.StreamWriter.write
写(数据)
Run Code Online (Sandbox Code Playgroud)Write data to the stream. This method is not subject to flow control. Calls to write() should be followed by drain().coroutine drain()
Run Code Online (Sandbox Code Playgroud)Wait until it is appropriate to resume writing to the stream. Example: writer.write(data) await writer.drain()
据我所知,
drain每次打电话都要write打电话.write将阻止循环线程那为什么写不是自动调用它的协同程序?为什么一个人打电话write而不必排水?我可以想到两个案例
write和close立即第一个是特例,我想我们可以有一个不同的api.缓冲应该在写入功能内部处理,应用程序不应该在意.
让我以不同的方式提出问题.这样做有什么缺点?python3.8版本有效吗?
async def awrite(writer, data):
writer.write(data)
await writer.drain()
Run Code Online (Sandbox Code Playgroud)
注意:draindoc明确说明如下:
当没有什么可以等待时,drain()立即返回.
再次阅读答案和链接,我认为这些功能是这样的.注意:检查已接受的答案以获得更准确的版本
def write(data):
remaining …Run Code Online (Sandbox Code Playgroud)