Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created August 17, 2019 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhewedy/3a982eef2fe05660d955b5fdbeaa93dc to your computer and use it in GitHub Desktop.
Save mhewedy/3a982eef2fe05660d955b5fdbeaa93dc to your computer and use it in GitHub Desktop.
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