超时长时间运行的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.

dongmangsha7354
dongmangsha7354 如果您用该评论回答该问题,我将选择它作为正确答案
2 年多之前 回复
doufeixi6014
doufeixi6014 不,您不能中断阻塞的cgo调用。您可能希望在一个单独的进程中运行这些函数,可以轻松地将其杀死和清理。
2 年多之前 回复

1个回答



只有两种方法可以中断cgo函数调用。 </ p>


  1. 使goroutine继续运行,但不再等待/阻止它,如上所示</ p> </ li>

  2. 放入 cgo背后的所有逻辑都在一个单独的可执行文件中调用,并在子进程中调用它。 </ p> </ li>
    </ ol>
    </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问