【发布时间】:2020-05-07 20:25:38
【问题描述】:
我正在尝试使用多个线程编写更快的 python 代码。我不想使用ProcessPoolExecutor 来保存内存消耗。
所以,当我使用 ThreadPoolExecutor.map 时,它将迭代器映射到函数。代码所花费的时间并没有真正得到增强,这真的不起作用。然后我在python中阅读了GIL,我的问题是:如果GIL适用于所有人,为什么他们创建ThreadPoolExecutor.map,或者有没有更好的想法使用ThreadPoolExecutor.map。
请找一个我用来理解这个过程的例子。我很高兴听到有关如何将多线程用于迭代器而不是多进程的建议,因为我的内存卡和 CPU 不是那么高。
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers = 4) as executor:
future= executor.map(is_prime, PRIMES)
print(future.result())
if __name__ == '__main__':
main()
【问题讨论】:
-
python 中的多线程在大多数情况下仅在涉及大量阻塞 I/O 操作(即网络爬虫)时才能提高效率。
-
非常感谢。似乎在 python 中使用线程不是一个好主意
标签: python python-multithreading threadpoolexecutor