首頁 > 後端開發 > Golang > 主體

在 golang 中等待函數完成

WBOY
發布: 2024-02-13 08:15:08
轉載
754 人瀏覽過

在 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()
}
登入後複製

以上是在 golang 中等待函數完成的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!