2024-04-28 05:48:10 发布
网友
我目前正在探索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():
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)]
您可以使用
threading.current_thread()
:这会产生如下结果:
相关问题 更多 >
编程相关推荐