Stopping Goroutines

To run a function in the background, it takes three keypresses; g, o and space.

DoSomething()
go DoSomething()

Stop channels

// a channel to tell it to stop
stopchan := make(chan struct{})
// a channel to signal that it's stopped
stoppedchan := make(chan struct{})
go func(){ // work in background // close the stoppedchan when this func
// exits
defer close(stoppedchan)
// TODO: do setup work
defer func(){
// TODO: do teardown work
}()
for {
select {
default:
// TODO: do a bit of the work case <-stopchan:
// stop
return
}
}
}()
log.Println("stopping...")close(stopchan)  // tell it to stop
<-stoppedchan // wait for it to have stopped
log.Println("Stopped.")

Introducing the Runner package

task := runner.Go(func(shouldStop runner.S) error {
// do setup work
defer func(){
// do tear-down work
}()
for {
// do stuff // periodically check to see if we should
// stop or not.
if shouldStop() {
break
}
}
return nil // no errors
})

Stopping the task

task.Stop()
select {
case <-task.StopChan():
// task successfully stopped
case <-time.After(10 * time.Second):
// task didn't stop in time
}
// execution continues once the code has stopped or has
// timed out.
// check task.Err() to see what it returned
if task.Err() != nil {
log.Fatalln("task failed:", task.Err())
}

Go Programming Blueprints #shamelessplug

--

--

--

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mat Ryer

Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

More from Medium

Verify Google Login Credentials with GOLang

Tarantool + golang: hello world

Tic-tac-toe and its applicability to nuclear war and WOPR

Coinbase Commerce with Golang