python 结束子线程并保证工作完成_python3中在线程中结束工作进程的方法

我想知道在python3中结束工作线程的方法。在

如果你看这个来自this question的代码示例,worker中有一个while True循环,我看到的是{}被调用了。在

为什么这个工人会自动结束?在

我特别感兴趣的是:

有哪些选项可以结束workers无限循环?

似乎唯一的选择是调用break或{},但我不确定这些是否会杀死线程。在

为了清楚起见,我实际上希望这个线程在其任务完成时死亡,而我看不到任何地方记录的杀死线程的方法。在#!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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值