我有以下代码用于创建线程并运行它们。
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
我们看到两个线程都具有相同的名称。我如何通过给它们起不同的名字来区分它们?这是否是并发类的功能?
非常感谢您的回答。
答案 0 :(得分:1)
您说:“两个线程都具有相同的名称”。
不对!名称相同是因为两个任务使用相同的线程:实际上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) 具有变量100的ThreadPoolExecutor-0_0: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) 具有变量100的ThreadPoolExecutor-0_1:4950
答案 1 :(得分:0)
来自docs:
3.6版中的新增功能:添加了thread_name_prefix参数以允许用户控制线程。由池创建的工作线程的线程名称可简化调试。