Home  >  Article  >  Backend Development  >  How to end a coroutine in golang

How to end a coroutine in golang

(*-*)浩
(*-*)浩Original
2019-12-27 11:14:584941browse

How to end a coroutine in golang

Goroutine and channel are great features of the Go language. They provide a very lightweight and easy-to-use concurrency capability. But when there are many goroutines in your application process, how to wait for all goroutines to exit in the main process?

1 Pass the exit signal through Channel (Recommended Learning: Go )

GO. Data is not shared through shared memory. The main process can send a stop signal to any goroutine through the channel, like the following:

func run(done chan int) {
        for {
                select {
                case <-done:
                        fmt.Println("exiting...")
                        done <- 1
                        break
                default:
                }
 
                time.Sleep(time.Second * 1)
                fmt.Println("do something")
        }
}
 
func main() {
        c := make(chan int)
 
        go run(c)
 
        fmt.Println("wait")
        time.Sleep(time.Second * 5)
 
        c <- 1
        <-c
 
        fmt.Println("main exited")
}

This method can stop the goroutine gracefully, but when there are too many goroutines, this method does not matter in terms of code appearance. It still seems clumsy in management.

2 Use waitgroup

The Waitgroup structure in the sync package is a good tool for synchronization between multiple goroutines provided by the Go language. The following is the official document's description of it:

Normally, we use waitgroup as follows:

Create an instance of Waitgroup, assuming we call it here wg

When each goroutine starts, call wg.Add(1). This operation can be called before the goroutine starts, or it can be called inside the goroutine. Of course, you can also call wg.Add(n)

before creating n goroutines. After each goroutine completes its task, call wg.Done()

and call it where you are waiting for all goroutines. wg.Wait(), it blocks before all goroutines that have executed wg.Add(1) have called wg.Done(), and it will return after all goroutines have called wg.Done().

The above is the detailed content of How to end a coroutine in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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