卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35536本站已运行397

在 golang 中等待函数完成

在 golang 中等待函数完成

在golang中,等待函数完成是一个常见的编程需求。无论是等待一个goroutine完成,还是等待一个channel中的数据到达,都需要合适的等待方式来处理。在这篇文章中,我们将向您介绍一些在golang中等待函数完成的方法和技巧。无论您是初学者还是有经验的开发者,本文都将为您提供有用的指导和示例代码,帮助您更好地处理等待函数完成的场景。让我们一起来深入了解吧!

问题内容

我在 golang 中有以下代码:

func A(){
  go print("hello")
}

func main() {
  A()
  // here I want to wait for the print to happen
  B()
}

如何确保 b() 仅在打印发生后才执行?

解决方法

使用sync.mutex

var l sync.mutex

func a() {
    go func() {
        print("hello")
        l.unlock()
    }()
}

func b() {
    print("world")
}

func testlock(t *testing.t) {
    l.lock()
    a()
    l.lock()
    // here i want to wait for the print to happen
    b()
    l.unlock()
}

使用sync.waitgroup

var wg sync.waitgroup

func a() {
    go func() {
        print("hello")
        wg.done()
    }()
}

func b() {
    print("world")
}

func testlock(t *testing.t) {
    wg.add(1)
    a()
    wg.wait()
    // here i want to wait for the print to happen
    b()
}

使用chan

func A() chan struct{} {
    c := make(chan struct{})
    go func() {     
        print("hello")
        c <- struct{}{}
    }()
    return c
}

func B() {
    print("world")
}

func TestLock(t *testing.T) {
    c := A()
    // here I want to wait for the print to happen
    <-c
    B()
}
卓越飞翔博客
上一篇: 加载docker镜像失败
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏