Home > Backend Development > Golang > How to Gracefully Wait for Go Routines to Finish: Boolean Channels vs. sync.WaitGroup?

How to Gracefully Wait for Go Routines to Finish: Boolean Channels vs. sync.WaitGroup?

DDD
Release: 2024-12-05 14:45:12
Original
939 people have browsed it

How to Gracefully Wait for Go Routines to Finish: Boolean Channels vs. sync.WaitGroup?

How to Gracefully Wait for Go Routines to Finish

When developing with Go, it's crucial to ensure that routines complete before exiting the program. Utilizing a boolean channel, as exemplified in the provided Playground link, can effectively achieve this.

Understanding the Channel Operation

The blocking operation <- done suspends program execution until a true or false value is sent through the channel. Hence, in the given code, the main() function waits until done receives the boolean true from the do_stuff routine.

Handling Deadlock Scenarios

Uncommenting the last line, <-done, results in a deadlock because the channel is empty. Without another routine sending values to it, the main() function remains blocked indefinitely. To avoid this situation, it's essential to ensure that a routine always sends a value through the channel when expected, signaling completion to the waiting function.

Alternative Approaches

While the boolean channel method is a simple solution, the sync package provides additional options for coordinating concurrent operations. Consider the following code:

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            longOp()
            wg.Done()
        }()
    }
    // Waits until all routines complete (wg.Done called 10 times)
    wg.Wait()
}

func longOp() {
    time.Sleep(time.Second * 2)
    fmt.Println("Long operation completed")
}
Copy after login

In this scenario, sync.WaitGroup is employed to track and synchronize concurrent routines, ensuring that main() waits for all routines to finish before continuing execution.

The above is the detailed content of How to Gracefully Wait for Go Routines to Finish: Boolean Channels vs. sync.WaitGroup?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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