Created
April 7, 2019 09:59
-
-
Save penglongli/47395e7e75472a7da92787f3eb8e947d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"sync" | |
"fmt" | |
) | |
var ( | |
num = 10 | |
) | |
func main() { | |
sig := make(chan int) | |
c1 := make(chan string) | |
c2 := make(chan string) | |
c3 := make(chan string) | |
var wg sync.WaitGroup | |
wg.Add(3) | |
go print(&wg, c1, "A") | |
go print(&wg, c2, "B") | |
go print(&wg, c3, "C") | |
go func() { | |
for { | |
select { | |
case <-sig: | |
// 检测到 sig 信号后退出 goroutine,避免出现 Deadlock | |
return | |
case str := <- c1: { | |
fmt.Println(str) | |
str = <- c2 | |
fmt.Println(str) | |
str = <- c3 | |
fmt.Println(str) | |
} | |
} | |
} | |
}() | |
wg.Wait() | |
sig <- 1 | |
} | |
func print(wg *sync.WaitGroup, c chan string, str string) { | |
defer wg.Done() | |
for i := 0; i < num; i++ { | |
c <- str | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment