Avi Mosseri
Avi Mosseri

Reputation: 1368

Timing Out A Long Running cgo Function Call

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.

Upvotes: 0

Views: 680

Answers (1)

Avi Mosseri
Avi Mosseri

Reputation: 1368

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.

Upvotes: 2

Related Questions