在 2 个 goroutine 之间同步

我的任务是同步 2 个 goroutines 所以输出应该是这样的:


foobarfoobarfoobarfoobar


.问题是,当我打电话给他们时,他们完全随机出现。这是我的代码:


package main


import (

    "fmt"

    "sync"

    "time"

)


type ConcurrentPrinter struct {

    sync.WaitGroup

    sync.Mutex

}



func (cp *ConcurrentPrinter) printFoo(times int) {

    cp.WaitGroup.Add(times)

    go func() {

        cp.Lock()

        fmt.Print("foo")

        cp.Unlock()

    }()

}

func (cp *ConcurrentPrinter) printBar(times int) {

    cp.WaitGroup.Add(times)

    go func() {

        cp.Lock()

        fmt.Print("bar")

        cp.Unlock()

    }()

}


func main() {

    times := 10

    cp := &ConcurrentPrinter{}


    for i := 0; i <= times; i++ {

        cp.printFoo(i)

        cp.printBar(i)

    }

    time.Sleep(10 * time.Millisecond)

}


牧羊人nacy
浏览 82回答 2
2回答

侃侃尔雅

如评论中所述,使用 goroutines 可能不是您要实现的目标的最佳用例 - 因此这可能是一个XY 问题。话虽如此,如果你想确保两个独立的 goroutines 以交替顺序交错它们的工作,你可以实现一组“乒乓”互斥锁:var ping, pong sync.Mutexpong.Lock() // ensure the 2nd goroutine waits & the 1st goes firstgo func() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; ping.Lock()&nbsp; &nbsp; &nbsp; &nbsp; foo()&nbsp; &nbsp; &nbsp; &nbsp; pong.Unlock()&nbsp; &nbsp; }}()go func() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; pong.Lock()&nbsp; &nbsp; &nbsp; &nbsp; bar()&nbsp; &nbsp; &nbsp; &nbsp; ping.Unlock()&nbsp; &nbsp; }}()https://go.dev/play/p/VO2LoMJ8fek

料青山看我应如是

使用频道:func printFoo(i int, ch chan<- bool, wg *sync.WaitGroup) {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("foo")&nbsp; &nbsp; &nbsp; &nbsp; ch <- true&nbsp; &nbsp; }()}func printBar(i int, ch chan<- bool, wg *sync.WaitGroup) {&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print("bar")&nbsp; &nbsp; &nbsp; &nbsp; ch <- true&nbsp; &nbsp; }()}func main() {&nbsp; &nbsp; times := 4&nbsp; &nbsp; firstchan := make(chan bool)&nbsp; &nbsp; secondchan := make(chan bool)&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; for i := 0; i <= times; i++ {&nbsp; &nbsp; &nbsp; &nbsp; printFoo(i, firstchan, &wg)&nbsp; &nbsp; &nbsp; &nbsp; <-firstchan&nbsp; &nbsp; &nbsp; &nbsp; printBar(i, secondchan, &wg)&nbsp; &nbsp; &nbsp; &nbsp; <-secondchan&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()}https://go.dev/play/p/MlZ9dHkUXGb
打开App,查看更多内容
随时随地看视频慕课网APP