go语言异步交叉输出abc


func consume() {
ch := make(chan string, 30)
wg := sync.WaitGroup{}
mu := sync.Mutex{}


wg.Add(1)
go func() {
defer wg.Done()
for {
mu.Lock()
if len(ch) == 30 {
mu.Unlock()
break
}
if len(ch)%3 == 0 {
ch <- "a"
}
mu.Unlock()
}
}()


wg.Add(1)
go func() {
defer wg.Done()
for {
mu.Lock()
if len(ch) == 30 {
mu.Unlock()
break
}
if len(ch)%3 == 1 {
ch <- "b"
}
mu.Unlock()
}
}()


wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-time.After(time.Second):
mu.Lock()
if len(ch)%3 == 2 {
ch <- "c"
}
if len(ch) == 30 {
mu.Unlock()
return
}
mu.Unlock()
}
}
}()


wg.Wait()
close(ch)


for i := 1; i <= 30; i++ {
fmt.Print(<-ch)
if i%3 == 0 {
fmt.Println()
}
}
}

 

 

posted @ 2022-06-15 21:34  知道了呀~  阅读(98)  评论(0编辑  收藏  举报