日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2025/3/20 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 结束子线程并保证工作完成_python3中在线程中结束工作进程的方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

我想知道在python3中結(jié)束工作線程的方法。在

如果你看這個(gè)來(lái)自this question的代碼示例,worker中有一個(gè)while True循環(huán),我看到的是{}被調(diào)用了。在

為什么這個(gè)工人會(huì)自動(dòng)結(jié)束?在

我特別感興趣的是:

有哪些選項(xiàng)可以結(jié)束workers無(wú)限循環(huán)?

似乎唯一的選擇是調(diào)用break或{},但我不確定這些是否會(huì)殺死線程。在

為了清楚起見(jiàn),我實(shí)際上希望這個(gè)線程在其任務(wù)完成時(shí)死亡,而我看不到任何地方記錄的殺死線程的方法。在#!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)

總結(jié)

以上是生活随笔為你收集整理的python 结束子线程并保证工作完成_python3中在线程中结束工作进程的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。