Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Channel synchronization in Go

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // the channel is used to notify main goroutine that the function completed successfully
    func worker(done chan bool) {
        fmt.Println("working...")
        time.Sleep(time.Second)
        fmt.Println("done")
    
        done <- true // send a value to indicate that the function completed successfully
    }
    
    func main() {
        done := make(chan bool, 1) // create a buffered channel for notification
        go worker(done) // run worker
    
        <-done // blocked until a notification is received from the worker from the channel
               // if you remove the line <- done the program will close before the worker starts
    }

    Channels can be used to synchronize execution between goroutines. Here is an example of using a channel to wait for a goroutine to complete.