Created
August 30, 2017 03:44
-
-
Save sh0umik/8d14b71b235932d61dcb346d3b12fb6b to your computer and use it in GitHub Desktop.
Go Routine Behaviour Controlling using Channel
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 | |
// 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 ( | |
"time" | |
"fmt" | |
) | |
// 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() | |
return | |
default: | |
for i :=0 ; i < 10; i++ { | |
fmt.Println(i) | |
} | |
time.Sleep(time.Second) | |
// 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 | |
fmt.Println(<-t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment