dryeyhe0266 2018-06-06 23:34
浏览 99
已采纳

超时长时间运行的cgo函数调用

I am currently working on a program which calls a long running function using a c library with cgo. I cannot edit the library to allow for timeouts using c. My only solution so far was to leave a zombie goroutine running

func Timeout(timeout time.Duration, runFunc func()) bool {
    var wg = new(sync.WaitGroup)
    c := make(chan interface{})
    wg.Add(1)
    go func() {
        defer close(c)
        wg.Wait()
    }()
    go func() {
        runFunc()
        c <- nil
        wg.Done()
    }()
    select {
    case <-c:
        return false
    case <-time.After(timeout):
        return true
    }
}

with the long running function working but this is for a long-running server which can lead to massive memory leaks/wasted cpu cycles over time.

  • 写回答

1条回答 默认 最新

  • dongmi3203 2018-06-18 18:49
    关注

    There are only two ways to interrupt a cgo function call.

    1. Leave the goroutine running but stop waiting/blocking on it as demonstrated above

    2. Put all of the logic behind the cgo call in a separate executable and call it within a subprocess.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 asp.textbox后台赋值前端不能显示什么原因
  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误