Golang : Stop goroutine without channel
Writing this down here as my own reference. In case you need to stop a goroutine from further execution and you cannot or do not want to use channel. You can use boolean variable as well.
In my previous tutorial on how to merge video and audio into a mp4 file, I need to stop goroutines that invoke the video camera and if the goroutine is not properly closed, it will cause segmentation fault.
Therefore, to stop the goroutine and prevent segmentation fault. Use :
var (
stopAudio = false
stopVideo = false
....
and when it is time to terminate the application, simply set the variable to true
fmt.Println("Cleaning up ...")
if key == 27 {
// stop audio first
stopAudio = true
and the in goroutine.
for {
if !stopAudio { // to prevent segmentation fault <---------------- HERE!
audioStream.Read()
fmt.Printf("\rRecording video and audio now. Wave or say something to your microphone! [%v]", ticker[rand.Intn(len(ticker)-1)])
// write to wave file
_, err := waveWriter.Write([]byte(framesPerBuffer)) // WriteSample16 for 16 bits
errCheck(err)
} else {
break
}
}
errCheck(audioStream.Stop())
audioStream.Close()
portaudio.Terminate()
...
Hope this helps!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.2k Golang : Convert(cast) string to rune and back to string example
+9.3k Golang : Generate random Chinese, Japanese, Korean and other runes
+6.4k Golang : Detect face in uploaded photo like GPlus
+25.7k Golang : missing Mercurial command
+46.6k Golang : Marshal and unmarshal json.RawMessage struct example
+29.5k Golang : How to create new XML file ?
+7.1k Nginx : How to block user agent ?
+5.3k PHP : See installed compiled-in-modules
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+12.4k Golang : Extract part of string with regular expression
+35.6k Golang : Smarter Error Handling with strings.Contains()
+13.7k Golang : Set image canvas or background to transparent