logo-MindMajix
PostGoLangGoLang
p
persis crystal

Posted on 3rd August 2020|1225 views

NaN
votes

Golang Channel Multiple Receivers

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

 

1 answers
Answers
P
naveen nani

Posted on 11th September 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

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo

  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos
Name
Course *
Email *
Phone Number