Skip to content

Instantly share code, notes, and snippets.

@hawx
Created January 2, 2016 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hawx/1482e7ebe2a6fd02ff52 to your computer and use it in GitHub Desktop.
Save hawx/1482e7ebe2a6fd02ff52 to your computer and use it in GitHub Desktop.
Example showing how to provide a blocking-close for long running processes in golang. The process will run until Close() is called, this call blocks until the process has actually stopped.
package main
import (
"log"
"time"
)
type Process struct {
quit chan struct{}
}
func NewProcess() *Process {
p := &Process{quit: make(chan struct{})}
go p.run()
return p
}
func (p *Process) run() {
loop:
for {
select {
case <-time.After(time.Second):
log.Println("tick")
case <-p.quit:
log.Println("break")
// simulate closing long task
time.Sleep(5 * time.Second)
break loop
}
}
// signal end of run()
close(p.quit)
}
func (p *Process) Close() {
// tell loop to break
p.quit <- struct{}{}
// wait for run() to finish
<-p.quit
}
func main() {
proc := NewProcess()
time.Sleep(2 * time.Second)
log.Println("closing proc")
proc.Close()
log.Println("proc closed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment