I have a grpc server which starts and stops a task. The task is run as a goroutine. I want to be able to forcefully stop the goroutine if a stop request is received regardless of what stage of execution the goroutine is in. The code looks similar to the following:
func Test() {
test1()
test2()
test3()
...
}
// in a grpc server method
go Test()
In this example, Test() takes a long time to complete (it controls some hardware which could take multiple seconds before a response is received). This Test() method is called from a parent as a goroutine.
I could use context or channels to stop the goroutine, however this means that I would need to check context everywhere throughout the method. In addition, there are some critical reasons for why I need the Test() method to end as abruptly as possible even if it is currently executing code that doesn't include the context checking logic.
I was reading that goroutines are meant to be stopped collaboratively. However since this option does not work for my use case, what other options do I have? Can I start a thread in go that is not a goroutine or are there any libraries that will let me achieve what I want?