Post

GoLangGoLang

p
persis crystal

Posted on 23rd April 2024|1219 views

0
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

 

Answers
P
naveen nani

Posted on 23rd April 2024

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