Created
July 30, 2017 16:59
-
-
Save ik5/5eab6ff778b8fcda11a8cc0ca8c5c752 to your computer and use it in GitHub Desktop.
Example on pause and resume threads in golang
This file contains hidden or 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