Why does Go uses channels to send and receive data between goroutines instead of using normal variables?

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

Why does Go uses channels to send and receive data between goroutines instead of using normal variables?

问题

我找不到关于这个问题的其他资料,除了维基百科上的这个解释https://en.wikipedia.org/wiki/Channel_(programming)。但是我对这个解释不满意。

通道解决了什么问题?
为什么我们不只是使用普通变量来发送和接收数据呢?

英文:

I could not find anything about this question except this explanation by Wikipedia https://en.wikipedia.org/wiki/Channel_(programming). But I'm not satisfied with the explanation.

What problem do channels solve?
Why don't we just use normal variables to send and receive data instead?

答案1

得分: 6

如果你所说的“普通变量”是指多个goroutine写入和读取的切片,那么这是一种保证会出现数据竞争的方式(你不希望出现数据竞争)。你可以通过使用某种同步机制(如Mutex或RWLock)来避免并发访问。

在这一点上,

  1. 你重新发明了通道(基本上就是在互斥锁下的切片)。
  2. 你花费了比你需要的更多的时间,而且你的解决方案仍然不如通道(没有语法支持,不能在select中使用切片等)。
英文:

If by "normal variables" you mean, for example, a slice that multiple goroutines write to and read from, then this is a guaranteed way to get data races (you don't want to get data races). You can avoid concurrent access by using some kind of synchronization (such as Mutex or RWLock).

At this point, you

  1. reinvented channels (which are basically that, a slice under a mutex)
  2. spent more time than you needed to and still your solution is inferior (there's no syntax support, you can't use your slices in select, etc.)

答案2

得分: 4

通道解决了并发读写的问题。基本上,它可以防止一个goroutine读取一个变量,而另一个goroutine写入相同的变量。

此外,通道可以有缓冲区,因此您可以在锁定之前写入多个值。

当然,您不一定非要使用通道。还有其他方法可以在goroutine之间发送数据。例如,您可以在分配或读取共享变量的值时使用原子操作,或者在访问共享变量时使用互斥锁。

英文:

Channels solve the problem of concurrent read and write. Basically, prevent the situation when one goroutine reads a variable and another one writes the same variable.

Also channels may have buffer, so you can write several values before locking.

Of course, you don't have to use channels. There are other ways to send data between goroutines. For example, you can use atomic operations when assigning or reading a value from a shared variable, or use mutex whenever you access it.

huangapple
  • 本文由 发表于 2021年7月22日 20:01:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/68484488.html
匿名

发表评论

匿名网友

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

确定