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.

2 snippets
  • How Select on Channel Works in Golang

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        // in this example we will choose between two channels
        c1 := make(chan string)
        c2 := make(chan string)
    
        go func() {
            time.Sleep(1 * time.Second)
            c1 <- "one"
        }()
    
        // each channel will receive a value after some time
        go func() {
            time.Sleep(2 * time.Second)
            c2 <- "two"
        }()
    
        // use select statement to wait for both values ​​at the same time,
        // printing each one as it arrives
        for i := 0; i < 2; i++ {
            select {
            case msg1 := <-c1:
                fmt.Println("received", msg1)
            case msg2 := <-c2:
                fmt.Println("received", msg2)
            }
        }
    }

    Select statement allows you to wait for multiple operations on a channel.

  • 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.