【问题标题】:How to give different names to ThreadPoolExecutor threads in Python如何在 Python 中为 ThreadPoolExecutor 线程赋予不同的名称
【发布时间】:2018-07-20 09:22:33
【问题描述】:

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

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()

当我在 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

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

非常感谢您的任何回答。

【问题讨论】:

  • 由于期货 api 本身目前似乎不支持此功能,因此在您在 submit 上提供的可调用文件中,尝试:threading.current_thread().setName()

标签: python-3.x multithreading concurrent.futures


【解决方案1】:

来自docs

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

使用 thread_name_prefix 参数:

concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')

【讨论】:

  • 有没有办法访问这个thread_name_prefix?我想访问这个名称并使其成为线程本地内存的一部分。
【解决方案2】:

您说:“两个线程具有相同的名称”。
这是不对的!名称相同,因为两个任务使用同一个线程:实际上 task() 立即退出。
为了让两个线程都参与,您必须在 task() 函数中添加一些睡眠。

回顾一下:

(1)不睡觉:

from concurrent.futures import ThreadPoolExecutor
import threading
import time

def task(n):
    result = 0
    i = 0
    for i in range(n): result = result + i
    print(f'{threading.current_thread().name} with variable {n}: {result}')
    
executor = ThreadPoolExecutor(max_workers=3)
executor.submit(task, (10))
executor.submit(task, (100))    

在这种情况下,输出将是:

ThreadPoolExecutor-0_0 变量 10: 45 ThreadPoolExecutor-0_0 变量为 100: 4950

(2) 在 task() 中加入睡眠, 使函数的时间更长:

from concurrent.futures import ThreadPoolExecutor
import threading
import time

def task(n):
    result = 0
    i = 0
    for i in range(n): result = result + i
    time.sleep(.5)
    print(f'{threading.current_thread().name} with variable {n}: {result}')

executor = ThreadPoolExecutor(max_workers=3)
executor.submit(task, (10))
executor.submit(task, (100)) 

在这种情况下,输出将是:

ThreadPoolExecutor-0_0 变量 10: 45 ThreadPoolExecutor-0_1 变量为 100: 4950

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 2023-03-27
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多