package main import ( "fmt" "sync" ) func ThreeG() { var ch1, ch2, ch3 = make(chan struct{}), make(chan struct{}), make(chan struct{}) var wg sync.WaitGroup wg.Add(3) go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch1 fmt.Println(s) ch2 <- struct{}{} } <-ch1 }("A") go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch2 fmt.Println(s) ch3 <- struct{}{} } }("B") go func(s string) { defer wg.Done() for i := 1; i <= 3; i++ { <-ch3 fmt.Println(s) ch1 <- struct{}{} } }("C") // 在向chan写入数据时,会阻塞当前协程,直到其他协程从该chan中读取了数据。 ch1 <- struct{}{} wg.Wait() } func NG(n int) { chanQueue := make([]chan struct{}, n) for i := 0; i < n; i++ { chanQueue[i] = make(chan struct{}) } var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { var preChan chan struct{} if i == 0 { preChan = chanQueue[n-1] } else { preChan = chanQueue[i-1] } curChan := chanQueue[i] go func(i byte, preChan, curChan chan struct{}, index int) { defer wg.Done() for k := 0; k < 5; k++ { <-preChan fmt.Printf("%c\n", i) curChan <- struct{}{} } if index == 0 { <-chanQueue[n-1] } }('A'+byte(i), preChan, curChan, i) } chanQueue[n-1] <- struct{}{} wg.Wait() fmt.Println("done") } func main() { }
标签:wg,ABC,struct,make,chan,sync,Golang,多线程 From: https://www.cnblogs.com/mainull/p/18081081