-
-
Save neutronstein/90cd5985eaefdeafca1d3fab58716760 to your computer and use it in GitHub Desktop.
Example on pause and resume threads in golang
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 ( | |
"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