总结
豆包 AI 助手文章总结
首页 > 后端开发 > Golang > 正文

在 golang 中等待函数完成

WBOY
发布: 2024-02-13 08:15:08
转载
860人浏览过

在 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

立即学习go语言免费学习笔记(深入)”;

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()
}
登录后复制

以上就是在 golang 中等待函数完成的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号