package main
import (
"context"
"errors"
"fmt"
"time"
)
type result struct {
record interface{}
err error
}
func longRun() {
for i := 0; ; i++ {
time.Sleep(1 * time.Second)
fmt.Println("This is very long running ", i)
}
}
func process() (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
quit := make(chan int)
go func() {
for {
select {
case <-quit:
fmt.Println("quit")
return
default:
longRun()
return
}
}
}()
select {
case <-ctx.Done():
close(quit)
return nil, errors.New("Execution canceled")
}
}
func main() {
value, err := process()
fmt.Println("value", value)
fmt.Println("err", err)
//prevent main function termination
for i := 0; ; i++ {
}
}
On timeout the goroutine in process() function terminates but how do i terminate the function longrun().
sample output
This is very long running 0
This is very long running 1
value <nil>
err Execution canceled
This is very long running 2
This is very long running 3
This is very long running 4
As output suggests longrun() function is still executing even after the process function has returned.
How do i terminate longrun() execution immediately after process() function is returned