Python 多线程:线程数

Python Multi-threading: Threads Number

我目前正在探索 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)

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

谢谢

您可以使用 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)]