Skip to content

Instantly share code, notes, and snippets.

@neutronstein
Forked from ik5/pause_resume.go
Created December 19, 2020 16:44
Show Gist options
  • Save neutronstein/90cd5985eaefdeafca1d3fab58716760 to your computer and use it in GitHub Desktop.
Save neutronstein/90cd5985eaefdeafca1d3fab58716760 to your computer and use it in GitHub Desktop.
Example on pause and resume threads in golang
package main
import (
"fmt"
"runtime"
"time"
)
// Thread stages
const (
Pause = "pause"
Run = "run"
Stop = "stop"
)
func myThread(stateChan <-chan string) {
state := Pause
for {
select {
case state = <-stateChan:
switch state {
case Pause:
fmt.Println("Pausing")
case Run:
fmt.Println("Starting")
case Stop:
fmt.Println("Stopping")
return
}
default:
// runtime.Gosched()
if state == Pause {
break
}
fmt.Println(time.Now())
}
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
ch := make(chan string)
go myThread(ch)
defer func() {
ch <- Stop
}()
ch <- Run
for i := 0; i < 1000000; i++ {
fmt.Println("Counter", i)
if i%50 == 0 {
ch <- Pause
time.Sleep(5 * time.Second)
ch <- Run
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment