44 Views

3rd August 2020

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

 

Answers

8th August 2020

Answered by naveen nani

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

GET STARTED

Speak with a Learning Advisor

Understand how the industry and practically oriented courses at Mindmajix transform your career.

  • 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