Wait for function to complete in golang

WBOY
Release: 2024-02-13 08:15:08
forward
753 people have browsed it

在 golang 中等待函数完成

In golang, waiting for a function to complete is a common programming requirement. Whether you are waiting for a goroutine to complete or waiting for data in a channel to arrive, you need to use a suitable waiting method to handle it. In this article, we will introduce you to some methods and techniques to wait for function completion in golang. Whether you are a beginner or an experienced developer, this article will provide you with helpful guidance and sample code to help you better handle waiting for functions to complete scenarios. Let’s take a closer look!

Question content

I have the following code in golang:

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

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

How to ensure that b() is only executed after printing has occurred?

Solution

Use 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()
}
Copy after login

Use 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()
}
Copy after login

Use 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()
}
Copy after login

The above is the detailed content of Wait for function to complete in golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!