Posted on 8th May 2025|1225 views
Why are multiple goroutines listening on one channel?
There are multiple goroutines in my code to receive over the same channel concurrently, but The message gets passed around all the goroutines.
x := make(chan string)
for j := 0; j < 5; j++ {
go func(j int) {
msg := <-x
x <- fmt.Sprintf("%s, hello from %d", msg, j)
}(j)
}
x <- "original"
fmt.Println(<-x)
Output:
original, hello from 0, hello from 1, hello from 2, hello from 3, hello from 4
Posted on 8th May 2025| views
Here is the alternative use GOMAXPROCS = NumCPU+1 like this
package main
import ( "fmt" "runtime" )
func main() {
runtime.GOMAXPROCS(runtime.NumCPU() + 1)
fmt.Print(runtime.GOMAXPROCS(0))
x := make(chan string)
for j := 0; j < 5; j++
{ go func(j int)
{ msg := <-x
x <- fmt.Sprintf("%s, hello from %d", msg, j) }
(i) }
x <- ", original"
fmt.Println(<-x) }
Output:
5, original, hello from 4