本文介绍了Linux、Mac 和 Windows 的硬递归限制是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 的 sys 模块 提供了一个函数 setrecursionlimit 允许您更改 Python 的最大递归限制.文档说:

Python's sys module provides a function setrecursionlimit that lets you change Python's maximum recursion limit. The docs say:

可能的最高限制取决于平台.

我的问题是:在 CPython 下,各种平台的最高限制是多少?我想知道 Linux、Mac 和 Windows 的值.

My question is: What is the highest possible limits for various platforms, under CPython? I would like to know the values for Linux, Mac and Windows.

更新:我们可以避免你做错了"的回答吗?我知道尝试进行非常深的递归通常是一个坏主意.我已经考虑了我的具体情况的利弊,并决定我想要这样做.

UPDATE: Can we please avoid "You're doing it wrong" answers? I know that trying to do very deep recursion is usually a bad idea. I've considered the pros and cons in my specific situation and decided that I want to do it.

推荐答案

在 Windows 上(至少),sys.setrecursionlimit 并不是全部.硬限制是基于每个线程的,一旦达到某个限制,您需要调用 threading.stack_size 并创建一个新线程.(我认为是 1MB,但不确定)我已经使用这种方法将其增加到 64MB 堆栈.

On Windows (at least), sys.setrecursionlimit isn't the full story. The hard limit is on a per-thread basis and you need to call threading.stack_size and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack.

import sys
import threading

threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(2 ** 20) # something real big
                               # you actually hit the 64MB limit first
                               # going by other answers, could just use 2**32-1

# only new threads get the redefined stack size
thread = threading.Thread(target=main)
thread.start()

我还没有尝试了解 threading.stack_size 可能存在哪些限制,但您可以随意尝试……这正是您需要查看的地方.

I haven't tried to see what limits there might be on threading.stack_size, but feel free to try... that's where you need to look.

总而言之,sys.setrecursionlimit 只是解释器本身强制执行的限制.threading.stack_size 允许您操纵操作系统施加的实际限制.如果您先达到后者的限制,Python 将完全崩溃.

In summary, sys.setrecursionlimit is just a limit enforced by the interpreter itself. threading.stack_size lets you manipulate the actual limit imposed by the OS. If you hit the latter limit first, Python will just crash completely.

这篇关于Linux、Mac 和 Windows 的硬递归限制是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:37