gpt4 book ai didi

python-3.x - 如何在 Python 中为 ThreadPoolExecutor 线程赋予不同的名称

转载 作者:行者123 更新时间:2023-12-01 02:38:38 25 4
gpt4 key购买 nike

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

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 类的一个特性?

非常感谢您的回答。

最佳答案

来自 docs :

New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.


使用 thread_name_prefix 参数:

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

关于python-3.x - 如何在 Python 中为 ThreadPoolExecutor 线程赋予不同的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com