Search code examples
gogoroutine

Cancel currently running function/goroutine


I'm using gin-gonic as HTTP handler. I want to prerender some graphical resources after my users make POST request. For this, I put a middleware that assign a function (with a timer inside) to a map[string]func() and call this function directly after assignation.

The problem is, when the user make two subsequent request, the function is called twice.

Is there any way to clear function ref and/or his currently running call like a clearInterval or clearTimeout in Javascript ?

Thanks


Solution

  • No; whatever function you've scheduled to run as a goroutine needs to either return or call runtime.Goexit.

    If you're looking for a way to build cancellation into your worker, Go provides a primitive to handle that, which is already part of any HTTP request - contexts. Check out these articles from the Go blog:

    Concurrency Patterns: Context

    Pipelines and cancellation