协程实现顺序打印123

参考解析

题目来源:

答案:

  1. package main
  2. import "fmt"
  3. var one = make(chan struct{}, 1)
  4. var two = make(chan struct{}, 1)
  5. var three = make(chan struct{}, 1)
  6. var done = make(chan struct{})
  7. func PrintOne() {
  8. defer close(one)
  9. for i := 0; i < 10; i++ {
  10. <-three
  11. fmt.Println("1")
  12. one <- struct{}{}
  13. }
  14. }
  15. func PrintTwo() {
  16. defer close(two)
  17. for i := 0; i < 10; i++ {
  18. <-one
  19. fmt.Println("2")
  20. two <- struct{}{}
  21. }
  22. }
  23. func PrintThere() {
  24. defer close(three)
  25. for i := 0; i < 10; i++ {
  26. <-two
  27. fmt.Println("3")
  28. three <- struct{}{}
  29. }
  30. done <- struct{}{}
  31. }
  32. func main() {
  33. defer close(done)
  34. three <- struct{}{}
  35. go PrintOne()
  36. go PrintTwo()
  37. go PrintThere()
  38. <-done
  39. }