package main

import (
    "fmt"
    "sync"
)

func main() {
    aChan := make(chan struct{})
    bChan := make(chan struct{})
    count := 5
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        for i := 0; i < count; i++ {
            <-aChan
            fmt.Println("A")
            bChan <- struct{}{}
        }
    }()

    go func() {
        defer wg.Done()
        for i := 0; i < count; i++ {
            <-bChan
            fmt.Println("B")
            // 死锁的坑,最后一个 B 打印完不用给 A 发信号了,A 的循环已退出
            if i == count-1 {
                return
            }
            aChan <- struct{}{}
        }
    }()

    aChan <- struct{}{}
    wg.Wait()
}

Output:

A
B
A
B
A
B
A
B
A
B