Home >Backend Development >Golang >Wait for function to complete in 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!
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() }
How to ensure that b() is only executed after printing has occurred?
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() }
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() }
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() }
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!