如何在 Python 中为 ThreadPoolExecutor 线程赋予不同的名称

use*_*151 5 multithreading python-3.x concurrent.futures

我有以下用于创建线程和运行它们的代码。

from concurrent.futures import ThreadPoolExecutor
import threading


def task(n):
    result = 0
    i = 0
    for i in range(n):
        result = result + i
    print("I: {}".format(result))
    print(f'Thread : {threading.current_thread()} executed with variable {n}')

def main():
    executor = ThreadPoolExecutor(max_workers=3)
    task1 = executor.submit(task, (10))
    task2 = executor.submit(task, (100))

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

当我在 Windows 10 机器上运行代码时,这是生成的输出:

I: 45
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 10
I: 4950
Thread : <Thread(ThreadPoolExecutor-0_0, started daemon 11956)> executed with variable 100

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

正如我们所见,这两个线程具有相同的名称。我如何通过给它们不同的名称来区分它们?这是否是 concurrent.futures 类的一个特性?

非常感谢您的回答。

osp*_*der 5

来自文档

3.6 版新增功能:添加了 thread_name_prefix 参数,以允许用户控制线程池创建的工作线程的线程名称,以便于调试。

使用 thread_name_prefix 参数:

并发.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')

  • 有没有办法访问这个“thread_name_prefix”?我想访问这个名称并使其成为线程本地内存的一部分。 (5认同)