In Go, sending on a closed channel will result in a runtime panic. To avoid this, you need to ensure that the channel is open before sending a value to it. There are various strategies to deal with this issue, such as using a boolean flag, utilizing the 'select' statement, or implementing a function that verifies the channel state. Below is an example illustrating how to avoid sending on a closed channel.
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 // sending data to the channel
}
close(ch) // closing the channel after sending
}()
go func() {
for {
val, ok := <-ch // check if the channel is still open
if !ok {
break // exit the loop if the channel is closed
}
fmt.Println(val) // process the received value
}
}()
wg.Wait() // wait for all goroutines 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?