Created
August 17, 2019 15:52
-
-
Save mhewedy/3a982eef2fe05660d955b5fdbeaa93dc to your computer and use it in GitHub Desktop.
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" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
wg.Add(2) | |
//waitForTaskPattern(&wg) | |
//waitForResultPattern(&wg) | |
waitForFinishPattern(&wg) | |
wg.Wait() | |
} | |
func waitForTaskPattern(wg *sync.WaitGroup) { | |
c := make(chan string) //unbuffered channel | |
go func() { | |
fmt.Println("start blocking the employee goroutine") | |
value := <-c | |
fmt.Println("received value:", value) | |
wg.Done() | |
}() | |
sd := time.Duration(rand.Intn(500)) * time.Millisecond | |
time.Sleep(sd) | |
c <- "hello" | |
fmt.Println("sending data") | |
wg.Done() | |
} | |
func waitForResultPattern(wg *sync.WaitGroup) { | |
c := make(chan string) | |
go func() { | |
time.Sleep(200 * time.Millisecond) | |
c <- "hello" | |
fmt.Println("sending value") | |
wg.Done() | |
}() | |
value := <-c | |
fmt.Println("received value:", value) | |
wg.Done() | |
} | |
func waitForFinishPattern(wg *sync.WaitGroup) { | |
c := make(chan struct{}) | |
go func() { | |
time.Sleep(200 * time.Millisecond) | |
close(c) | |
fmt.Println("sending close signal") | |
wg.Done() | |
}() | |
_, wd := <-c | |
fmt.Println("receive data?", wd) | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment