Identify and stop a goroutine 2

Hello everyone,

I’m trying to migrate some of my bash scripts to golang since it is a great language in my point of view.
But I’m facing an issue with goroutines that I could not solve by researching here or on stackoverflow.

Here is my project :
I have a webserver with two endpoints; One is adding one task at a time, the other one is stopping one task at a time (let’s say the first placed to simplify).
On startup the webserver is starting some tasks too.
Tasks here are long run computational calculations.
The project is capable to have multiple tasks in concurrence (or parallel; non blocking).

Here is an example :

func main() {

    for i := 0; i < 10; i++ {
        addTask()
    }

    http.HandleFunc("/addtask", addTask)
    http.HandleFunc("/stoptask", stopTask)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

func addTask() {
    go task() // start a goroutine
}

func stopTask() {
    // here is the mystery, should I use a context.WithCancel() or a channel to stop a task, or maybe something else?
}

// here is the task that I am trying to stop. Should stop execution at any time; during one of the computations or the sleeps (should be equivalent to SIGKILL)
func task() {
    longComputationalCalculation() // can take some minutes to complete
    time.Sleep(time.Duration(time.Second * 30)) // sleep for 30s before the second calculation
    longComputationalCalculation2() // take the result of the first calculation in parameter; can also take some minutes to complete
    time.Sleep(time.Duration(time.Second * 30)) // sleep for 30s at the end
}

A lot of examples here and there are performed with context.WithTimeout() or with timer.Sleep(). But here I have real computations to perform and they should perform unless the user wants to stop one of them.

With bash I would start this task in a new session and if I would kill it I would send a pkill on the session.

Thank you in advance for taking the time to read my project and again if you can lead me to a solution.

Best regards

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.