Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Go Routine Behaviour Controlling using Channel
package main
// Problem :
// Create a go routine that will loop and sleep for 1 second. When it wakes up it will print out the time.
//The main routine will wait for 20 seconds and then sends a termination signal to the go routine.
import (
// work has two channel one for controlling the chanel and other for getting the
// output out of the channel before quiting , like the duration of the routine in this case
func work(quit chan bool, t chan string, start time.Time, elapse time.Duration) {
select {
case <- quit:
t <- elapse.String()
for i :=0 ; i < 10; i++ {
// It wakes up and prints how many time it slept !
fmt.Println("1 Sec Sleep")
elapse = time.Since(start)
// Loop until you get the signal form chanel quit
work(quit, t, start, elapse)
func main(){
// two channel initialization
t := make(chan string)
quit := make(chan bool)
// start time is now and elapse time is 0
start := time.Now()
elapse := 0 * time.Microsecond
// start the go routine passing all the parameter
go work(quit, t, start, elapse)
// sleep the main routine for 20 sec while the work routine still working
time.Sleep(20 * time.Second)
// send quit signal to the work channel
quit <- true
// print the result from the work channel , in this case the duration time the channel is up or working
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment