Go Gopher How to Go

Channel Synchronization

We can use channels to synchronize execution across goroutines. Here's an example of using a blocking receive to wait for a goroutine to finish. This is a powerful way to orchestrate complex concurrent operations.

💡 Key Points

  • Channels can be used to synchronize execution across goroutines.
  • A blocking receive on a channel can be used to wait for a goroutine to finish.
  • This pattern is useful for ensuring that a goroutine has completed its work before the main program exits.
  • The value sent on the channel can be used to signal completion or pass data.
  • A buffered channel of size 1 can be used to avoid blocking the sender if the receiver is not ready.

Channel Synchronization Example

In this example, we'll use a channel to block the `main` goroutine until the `worker` goroutine has finished.

package main

import (
    "fmt"
    "time"
)

func worker(done chan bool) {
    fmt.Print("working...")
    time.Sleep(time.Second)
    fmt.Println("done")

    done <- true
}

func main() {
    done := make(chan bool, 1)
    go worker(done)

    <-done
}
Output:
working...done

Synchronization Patterns

PatternDescriptionExample
Wait for one goroutineA single <-done waits for one goroutine.&lt;-done
Wait for multiple goroutinesUse a for loop to wait for multiple signals.for i := 0; i &lt; N; i++ { &lt;-done }
Using sync.WaitGroupA more idiomatic way to wait for multiple goroutines.wg.Wait()