Skip to content

Instantly share code, notes, and snippets.

@shanehou
Last active April 6, 2017 13:51
Show Gist options
  • Save shanehou/b74a8916a1bd8bf00e30e67d5ee3817f to your computer and use it in GitHub Desktop.
Save shanehou/b74a8916a1bd8bf00e30e67d5ee3817f to your computer and use it in GitHub Desktop.
一个Golang并发同步问题
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func a(i int, cs chan<- int) {
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
fmt.Printf("performing a(%+v)...\n", i)
cs <- i
}
func b(i int) {
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
fmt.Printf("performing b(%+v)...\n", i)
}
func c(i int) {
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
fmt.Printf("performing c(%+v)..........\n", i)
}
func d(i int) {
fmt.Printf("performing d(%+v)\n", i)
}
func main() {
list := []int{4, 1, 5, 2, 6, 3, 7}
cs := make(chan int, len(list))
var final sync.WaitGroup
final.Add(len(list))
for _, i := range list {
var wg sync.WaitGroup
wg.Add(2)
go a(i, cs)
go func(i int, wg *sync.WaitGroup) {
defer wg.Done()
b(i)
}(<-cs, &wg)
go func(i int, wg *sync.WaitGroup) {
defer wg.Done()
c(i)
}(i, &wg)
go func(i int, wg *sync.WaitGroup) {
defer final.Done()
wg.Wait()
d(i)
}(i, &wg)
}
final.Wait()
fmt.Println("all done.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment