Python3中在线程中结束辅助进程的方法
我想知道如何在Python3中结束工作线程 如果您查看来自Python3中在线程中结束辅助进程的方法,python,multithreading,Python,Multithreading,我想知道如何在Python3中结束工作线程 如果您查看来自worker的这个代码示例,其中有一个while True循环,我看到的是调用了q.task_done() 为什么这个工人会自动结束 我特别感兴趣的是: 有哪些选项可以结束workers无限循环? 看起来唯一的选择是调用break或return,但我不确定这些是否会杀死线程 要明确的是,我实际上希望这个线程在其任务完成后死亡,我看不到任何地方记录的杀死线程的方法 #!python3 import threading from queue
worker
的这个代码示例,其中有一个while True
循环,我看到的是调用了q.task_done()
为什么这个工人会自动结束
我特别感兴趣的是:
有哪些选项可以结束workers无限循环?
看起来唯一的选择是调用break
或return
,但我不确定这些是否会杀死线程
要明确的是,我实际上希望这个线程在其任务完成后死亡,我看不到任何地方记录的杀死线程的方法
#!python3
import threading
from queue import Queue
import time
# lock to serialize console output
lock = threading.Lock()
def do_work(item):
time.sleep(.1) # pretend to do some lengthy work.
# Make sure the whole print completes or threads can mix up output in one line.
with lock:
print(threading.current_thread().name,item)
# The worker thread pulls an item from the queue and processes it
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
# Create the queue and thread pool.
q = Queue()
for i in range(4):
t = threading.Thread(target=worker)
t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
t.start()
# stuff work items on the queue (in this case, just a number).
start = time.perf_counter()
for item in range(20):
q.put(item)
q.join() # block until all tasks are done
# "Work" took .1 seconds per task.
# 20 tasks serially would be 2 seconds.
# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
print('time:',time.perf_counter() - start)
有哪些选项可以结束workers无限循环
使用while循环轮询threading.semaphore
对象实例,而不是常量True
boolean。当您想要杀死工作线程时,从杀死线程发出信号,它将退出循环
如果希望主线程等待辅助线程完成,则向信号量发送信号,然后执行thread.join()
以阻止主线程,直到辅助线程完成它需要执行的任何操作。记住先发信号,否则它会挂起;)
这就是说,您已经对线程进行了守护,因此不需要杀死它。当没有任何非守护进程线程处于活动状态时,进程将死亡。更新以删除守护进程效果,因为您希望线程干净地退出,只需删除以下行:
t.daemon = True # thread dies when main thread (only non-daemon thread) exits.