Skip to content

Commit

Permalink
Merge pull request lifei6671#62 from metrue/patch-1
Browse files Browse the repository at this point in the history
a solution with channel only
  • Loading branch information
lifei6671 authored Dec 8, 2022
2 parents 178b515 + d575a4d commit 94a1f2b
Showing 1 changed file with 58 additions and 3 deletions.
61 changes: 58 additions & 3 deletions question/q001.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

**源码参考**

```
```go
letter,number := make(chan bool),make(chan bool)
wait := sync.WaitGroup{}

Expand Down Expand Up @@ -57,6 +57,61 @@

**源码解析**

这里用到了两个`channel`负责通知,letter负责通知打印字母的goroutine来打印字母,number用来通知打印数字的goroutine打印数字。
这里用到了两个`channel`负责通知,letter负责通知打印字母的goroutine来打印字母,number用来通知打印数字的goroutine打印数字。wait用来等待字母打印完成后退出循环。


也可以分别使用三个 channel 来控制数字,字母以及终止信号的输入.

```go

package main

wait用来等待字母打印完成后退出循环。
import "fmt"

func main() {
number := make(chan bool)
letter := make(chan bool)
done := make(chan bool)

go func() {
i := 1
for {
select {
case <-number:
fmt.Print(i)
i++
fmt.Print(i)
i++
letter <- true
}
}
}()

go func() {
j := 'A'
for {
select {
case <-letter:
if j >= 'Z' {
done <- true
} else {
fmt.Print(string(j))
j++
fmt.Print(string(j))
j++
number <- true
}
}
}
}()

number <- true

for {
select {
case <-done:
return
}
}
}
```

0 comments on commit 94a1f2b

Please sign in to comment.