一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述

栏目: Go · 发布时间: 6年前

内容简介:在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

背景

在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

步骤

实现函数 RecursiveDepthChecker

func RecursiveDepthChecker(max int) bool {
    //注意,这里我们跳过了本函数自己的栈,找到父调用的函数名
    caller, _, _, _ := runtime.Caller(1)
    currentFuncName := runtime.FuncForPC(caller).Name()
    stack := make([]byte, 65535*1) //max 1MB stack traceback
    //由于Golang Runtime中很多关于栈的函数未导出,无法使用。因此使用最肮脏的字符串检测方法
    runtime.Stack(stack, false)
    start := 0
    depth := 0
    for {
        count := strings.Index(string(stack[start:]), currentFuncName)
        if count >= 0 {
            start += count + len(currentFuncName)
            depth++
        } else {
            break
        }
    }

    if depth > max {
        return false
    }
    return true
}

在需要进行检测的函数用引入检查即可

func TFunc() {
    fmt.Println("Start Caller...")
    if !RecursiveDepthChecker(5) {
        fmt.Println("Stack Overflow")
        return
    }
    TFunc()
}

以上所述就是小编给大家介绍的《一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Foundations of PEAR

Foundations of PEAR

Good, Nathan A./ Kent, Allan / Springer-Verlag New York Inc / 2006-11 / $ 50.84

PEAR, the PHP Extension and Application Repository, is a bountiful resource for any PHP developer. Within its confines lie the tools that you need to do your job more quickly and efficiently. You need......一起来看看 《Foundations of PEAR》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码