Golang将相同的数据分发给Go协程。

huangapple go评论85阅读模式
英文:

Golang dispatch same data to go routins

问题

有一个Go协程生成数据。还有很多Go协程处理HTTP响应。我希望生成的数据能够传递给所有的HTTP处理程序。所有分发的数据都是相同的。
我考虑了两种解决方案。一种是使用通道管道进行扇出,另一种是使用互斥锁和条件变量。
我担心前一种方法是否需要在通道中进行内存分配。

我应该选择哪种方法?

英文:

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?

答案1

得分: 0

你的用例听起来可以从通道中受益。通常情况下,当需要在Go协程之间进行通信时,首选通道。听起来像是一个经典的工作池的例子。

互斥锁用于保护一块内存,以便只有一个goroutine可以同时访问/修改它。通常情况下,这与人们想要的相反,人们希望并行执行。

一个好的经验法则是,在实际成为问题之前,不要担心优化(内存分配与否)。过早优化是一种常见的反模式。

英文:

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.

huangapple
  • 本文由 发表于 2022年1月7日 01:08:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70610864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定