Channel Synchronization
This Go code showcases the use of a channel (done
) to signal the completion of work in a goroutine.
Let's break it down with inline comments:
Output
Explanation:
package main
: Indicates that this Go file belongs to the main executable package.import (...)
: Imports necessary packages, including "fmt" for formatting and printing, and "time" for handling time-related operations.func worker(done chan bool) { ... }
: Defines a functionworker
that takes a channeldone
as a parameter. This function simulates work by printing messages, sleeping for one second, and then sending a signal (true
) through the channel to indicate that the work is complete.func main() { ... }
: The main function, where the execution of the program begins.done := make(chan bool, 1)
: Creates a buffered channel named 'done' with a capacity of 1. The buffer size ensures that the channel can hold one value without requiring a corresponding receiver to be ready.go worker(done)
: Launches a new goroutine to execute theworker
function with thedone
channel as a parameter.<-done
: Blocks the main goroutine until a value is received from thedone
channel. This serves as a synchronization point, ensuring that the main goroutine waits until the worker goroutine has completed its work and sent the signal.
In summary, this code demonstrates how to use a channel to signal the completion of work between goroutines. The main goroutine launches a worker goroutine, and the main goroutine waits for a signal from the worker before proceeding further. This pattern is commonly used for synchronization in concurrent programming.
Last updated
Was this helpful?