Created
January 2, 2016 14:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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