python递归深度,python多线程“最大递归深度超过”

I use Python multithread to realize Quicksort.

Quicksort is implement in a function. It is a recursive function.

Each thread calls Quicksort to sort the array it has. Each thread has its own array that stores the numbers needs to be sorted.

If the array size is smaller (<10,000). It runs ok.

However, if the array size is larger, it shows the "maximum recursion depth exceed".

So, I use setrecursionlimit () function to reset the recursion depth to 1500. But the program crash directly...

The following is quicksort code. It works well if not in multi-thread environment.

It seems multiple threads is the cause of recursion depth problem.

def partition (array, p, r):

x = array[r]

i = (p-1)

j = p

while (1):

if array[j] <= x:

i = (i+1)

temp = array[j]

array[j] = array[i]

array[i] = temp

j+=1

if j == r:

break

temp = array[i+1]

array[i+1] = array[r]

array[r] = temp

return i+1

def quicksort (array, p, r):

if p < r:

q = partition (array, p, r)

quicksort (array, p, q-1)

quicksort (array, q+1, r)

解决方案

It sounds like your real question is "Why is the recursion depth shorter when using threads"? I will try to answer that question.

First, background. Each level of recursion is stored an area of memory known as the stack. Unfortunately, the system has to allocate the stack space in advance and it doesn't know in advance how much stack space your program might need. That's why too much recursion causes a "maximum recursion depth" error: your program has used up all of that stack space.

Each thread needs its own stack to store the list of functions that are currently executing in that thread. In a single threaded program, the system can afford to give a big chunk of memory to the stack for that one thread. In a multi-threaded program, the system has to be a bit more conservative and it gives only a small stack to each thread. Otherwise, a program with many threads could quickly use up all system memory just with stack space (most of which won't be used).

All of this is done by the operating system and/or by the C library, which Python (more precisely, CPython) runs on top of. Python tries hard to prevent you from using the entire C stack, because that would cause a hard crash rather than simply an exception. You can tell Python how to behave with the setrecursionlimit function, but that doesn't change the actual amount of stack space available.

On a unix-ish system with a bash shell, you may be able to change the stack size with the ulimit -s command. Type help ulimit at your bash shell prompt for more information.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值