如何修改一行Python代码实现ThreadPoolExecutor线程编号打印
问题:为ThreadPoolExecutor线程任务输出添加线程编号
现有一段使用concurrent.futures.ThreadPoolExecutor的Python代码,当前执行后输出如下:
MainThread done at sec 1 MainThread done at sec 1 MainThread done at sec 2 MainThread done at sec 1 MainThread done at sec 0 MainThread done at sec 3 MainThread done at sec 2 MainThread done at sec 5 MainThread done at sec 4
需要修改为带线程编号的输出,示例如下:
MainThread 1 done at sec 1 MainThread 3 done at sec 1 MainThread 2 done at sec 2 MainThread 3 done at sec 1 MainThread 1 done at sec 0 MainThread 2 done at sec 3 MainThread 2 done at sec 2 MainThread 3 done at sec 5 MainThread 1 done at sec 4
要求仅修改以下代码行实现需求:
print(threading.current_thread().name + ' done at sec ' + str(future.result()))
完整代码如下:
import concurrent.futures import threading import pdb import time import random def Threads2(time_sleep): time.sleep(time_sleep) return time_sleep all_sections = [random.randint(0, 5) for iii in range(10)] test1 = [] with concurrent.futures.ThreadPoolExecutor(max_workers=3, thread_name_prefix="Ok") as executor: working_threads = {executor.submit(Threads2, time_sleep): time_sleep for index, time_sleep in enumerate(all_sections)} for future in concurrent.futures.as_completed(working_threads): print(threading.current_thread().name + ' done at sec ' + str(future.result()))
解决方案
当前代码中threading.current_thread().name获取的是执行print语句的主线程名称,而非执行任务的工作线程。要获取执行任务的工作线程编号,可通过Future对象的私有属性_thread获取对应的工作线程,再提取编号:
修改后的代码行如下:
print(f"MainThread {future._thread.name.split('Ok')[1]} done at sec {future.result()}")
说明:
future._thread指向执行该任务的工作线程对象;- 工作线程名称由
thread_name_prefix(此处为"Ok")加编号组成,通过split('Ok')[1]提取出编号; - 使用f-string简化字符串拼接,使代码更清晰。
执行修改后的代码,即可得到符合要求的带线程编号的输出。
内容的提问来源于stack exchange,提问作者Rhys
相关产品推荐
相关产品推荐

