```
package main
import (
"fmt"
"sync"
)
var zf []string = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
func PrintZF(zfc chan int, nc chan int, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 26; i++ {
select {
case <-zfc:
fmt.Println(zf[i])
nc <- 1
}
}
}
func PrintN(zfc chan int, nc chan int, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 26; i++ {
select {
case <-nc:
fmt.Println(i)
zfc <- 1
}
}
}
func main() {
wg := &sync.WaitGroup{}
// 1 防止: 两个协程,其中一个结束,另一个仍向通道中写入数据,导致死锁
zfc := make(chan int, 1)
nc := make(chan int, 1)
wg.Add(1)
go PrintZF(zfc, nc, wg)
wg.Add(1)
go PrintN(zfc, nc, wg)
zfc <- 1
wg.Wait()
close(zfc)
close(nc)
}
```
```go
package main
import (
"fmt"
"runtime"
"sync"
)
var zf []string = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
func PrintZF() {
defer wg.Done()
for i := 0; i < 26; i++ {
fmt.Println(zf[i])
runtime.Gosched()
}
}
func PrintN() {
defer wg.Done()
for i := 0; i < 26; i++ {
fmt.Println(i)
runtime.Gosched()
}
}
var wg sync.WaitGroup
func main() {
runtime.GOMAXPROCS(1)
wg.Add(1)
go PrintZF()
wg.Add(1)
go PrintN()
wg.Wait()
}
```
#1
更多评论
```go
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
runtime.GOMAXPROCS(1)
limit := 26
//输出字母
go func() {
defer wg.Done()
for i := 0; i < limit; i++ {
fmt.Printf("%c\n", 'a'+i)
runtime.Gosched()
}
}()
//输出数字
go func() {
defer wg.Done()
for i := 0; i < limit; i++ {
fmt.Println(i)
runtime.Gosched()
}
}()
wg.Wait()
}
```
#2
```go
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
wg.Add(2)
limit := 26
numChan := make(chan int, 1)
charChan := make(chan int, 1)
charChan <- 1
go func() {
defer wg.Done()
for i := 0; i < limit; i++ {
<-charChan
fmt.Printf("%c\n", 'a'+i)
numChan <- 1
}
}()
go func() {
defer wg.Done()
for i := 0; i < limit; i++ {
<-numChan
fmt.Println(i)
charChan <- 1
}
}()
wg.Wait()
close(charChan)
close(numChan)
}
```
#3