gpt4 book ai didi

python - pow 函数使用 ThreadPoolExecutor 阻塞所有线程

转载 作者:行者123 更新时间:2023-12-01 00:49:23 25 4
gpt4 key购买 nike

尽管有关 ThreadPoolExecutor 的第一个示例使用 pow 函数 ( https://docs.python.org/3/library/concurrent.futures.html ),但使用 pow 似乎会在调用时异常阻止所有线程。请参阅下面的代码。

from concurrent.futures import ThreadPoolExecutor
import time

executor = ThreadPoolExecutor(max_workers=16)

def blocking():
i = 0
while True:
time.sleep(1)
i+=1
print("block",i)
if i>3:
print("Starting pow....")
break
block= pow(363,100000000000000)
return True

def non_blocking():
i = 0
while True:
time.sleep(1)
i+=1
print("non",i)

return True

f1 = executor.submit(blocking)
f2 = executor.submit(non_blocking)

我期望的输出:

block 1
non 1
block 2
non 2
block 3
non 3
block 4
Starting pow....
non 4
non 5
non 6
non 7
non 8

但是程序在“starting pow....”后停止运行,给出结果:

block 1
non 1
block 2
non 2
block 3
non 3
block 4
Starting pow....

最佳答案

你的Python实现(可能是CPython)必须有Global Interpreter Lock (吉尔)

pow 是一个原生 Python 函数,它在调用时不会释放 GIL,从而在运行时有效地阻止所有执行,并且运行相当长一段时间。

如果你想要非阻塞,请使用 ProcessPoolExecutor反而。一个单独的进程意味着 2 个单独的 GIL 并且不会阻塞。它具有完全相同的界面。它还具有更多限制,因为它要求参数可挑选(没有像线程那样方便的共享内存)

请注意,此计算可能永远不会结束或以“内存不足错误”结束:因为它是具有幂值的整数之间的幂,所以它不会像 float 那样溢出,但是计算啊计算,每次都会产生越来越大的整数

该数字的估计位数大致为:

>>> math.log10(363)*100000000000000
255990662503611.25

10^14 位数字,比当前任何计算机在内存和 CPU 方面都能处理的数字还要多。

关于python - pow 函数使用 ThreadPoolExecutor 阻塞所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com