我正在探索python threading的选项。
我看到这种示例有一个线程池
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)
唯一的问题是我想知道哪个线程是运行的函数。有没有办法做到这一点?
由于
答案 0 :(得分:0)
您可以使用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)]