Python多线程:线程数

2024-04-28 05:48:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在探索python线程的选项。你知道吗

我见过这样的例子,有一个线程池

from multiprocessing.dummy import Pool as ThreadPool

def function(x):
    return x * x

pool = ThreadPool(4)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pool.map(function, array)

唯一的问题是我想知道函数运行在哪个线程中。有什么办法吗?你知道吗

谢谢


Tags: fromimportreturndefas选项function线程
1条回答
网友
1楼 · 发布于 2024-04-28 05:48:10

您可以使用threading.current_thread()

from multiprocessing.dummy import Pool as ThreadPool
from threading import current_thread

def function(x):
    return (current_thread().name, x * x)

pool = ThreadPool(4)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(pool.map(function, array))

这会产生如下结果:

[('Thread-1', 1), ('Thread-1', 4), ('Thread-1', 9), ('Thread-3', 16), ('Thread-3', 25), ('Thread-3', 36), ('Thread-1', 49), ('Thread-4', 64), ('Thread-2', 81), ('Thread-2', 100)]

相关问题 更多 >