Go by Example: Channel Synchronization

Here’s an example to demonstrate channel synchronization:

package main

import "fmt"
import "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
}

In this example, we create a channel done and a function worker that takes the channel as an argument. The worker function does some work, waits for a second and then sends a value true to the channel done.

In the main function, we start the worker function as a goroutine and then use the <-done statement to wait for a value to be sent to the channel. This wait operation blocks the main function until the value is received, ensuring that the worker function has completed before the main function continues.

Here’s one more example to demonstrate channel synchronization:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Printf("Worker %d starting\n", id)
    // time-consuming task
    time.Sleep(time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }
    wg.Wait()
    fmt.Println("All workers done")
}

In this example, we use the sync.WaitGroup to manage the goroutines and make sure all of them complete before the program terminates. The wg.Add(1) statement adds the number of goroutines to the WaitGroup, and the defer wg.Done() statement decrements the number of goroutines in the WaitGroup once the function worker returns. The wg.Wait() statement blocks the main function until the number of goroutines in the WaitGroup becomes 0. This way, the main function can ensure all the goroutines are done before it terminates.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *