Home > OS >  Golang dispatch same data to go routins
Golang dispatch same data to go routins

Time:01-07

There is one go routine generating data. Also are many go routines that handles http response. I want generated data to be passed to all http handler routines. All dispatched data are same. I thought two solutions. Using channel pipeline to fan-out or using mutex and condition variable. I concern if former way needs memory allocation to put data in channel.

What should I choose?

CodePudding user response:

Your use case sounds like it benefits from channels. In general channels are preferred when communication between go routines is needed. Sounds like a classic example of a worker pool.

Mutexes are used to protect a piece of memory, so only 1 goroutine can access/modify it at a time. Often times this is the opposite of what people want, which is to parallelize execution.

A good rule of thumb is to not worry about optimization(memory allocation or not) until it actually becomes an issue. Premature optimization is a common anti-pattern.

  •  Tags:  
  • Related