I have three functions which prints First
, Second
and Third
.
I want to print it in the order First
then Second
and then Third
via concurrency (channels)
我正面临着按顺序排列的问题。 谁能帮助我如何实现秩序?
package main
import (
"fmt"
"sync"
)
type firstSecondThird struct {
n int
}
var (
wg sync.WaitGroup
first chan bool
second chan bool
third chan bool
)
func init() {
first = make(chan bool)
second = make(chan bool)
// third = make(chan bool)
}
func (fn firstSecondThird) first() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
fmt.Print("First")
first <- true
}
}
func (fn firstSecondThird) second() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
<-first
fmt.Print("Second")
second <- true
}
}
func (fn firstSecondThird) third() {
defer wg.Done()
for i := 0; i < fn.n; i++ {
<-second
fmt.Print("Third")
// third <- true
}
}
func main() {
firstSecondThird := firstSecondThird{
n: 4,
}
wg.Add(2)
go firstSecondThird.first()
go firstSecondThird.second()
go firstSecondThird.third()
// <-third
wg.Wait()
}
<<>Output>:
FirstFirstSecondSecondFirstThirdThirdSecondThirdFirstSecond%