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
+12.7k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+5.3k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+10.1k Golang : Select region of interest with mouse click and crop from image
+8.6k Golang : Get SPF and DMARC from email headers to fight spam
+12k Golang : Extract part of string with regular expression
+11.7k Golang : Simple client-server HMAC authentication without SSL example
+24.6k Golang : Storing cookies in http.CookieJar example
+21.9k Golang : Read directory content with filepath.Walk()
+11.1k Golang : Generate DSA private, public key and PEM files example
+5.4k Golang : Find change in a combination of coins example
+6k Unix/Linux : Use netstat to find out IP addresses served by your website server
+51.5k Golang : How to get time in milliseconds?