In Go, closing a channel is an important operation that indicates that no more values will be sent on the channel. This allows other goroutines to detect when the channel has been closed and can help prevent deadlocks. It's important to note that you should only close a channel from the sending side and not from the receiving side or multiple goroutines concurrently.
To close a channel, you can use the built-in close
function. Here's a simple example:
package main
import (
"fmt"
"sync"
)
func main() {
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // Closing the channel after sending all values
}()
go func() {
for val := range ch {
fmt.Println(val) // Reading values from the channel until it's closed
}
}()
wg.Wait() // Wait for the goroutine to finish
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?