Skip to content

Instantly share code, notes, and snippets.

@ik5
Created July 30, 2017 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ik5/5eab6ff778b8fcda11a8cc0ca8c5c752 to your computer and use it in GitHub Desktop.
Save ik5/5eab6ff778b8fcda11a8cc0ca8c5c752 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