Berke Kaan Cetinkaya
Berke Kaan Cetinkaya

Reputation: 828

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

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?

Upvotes: 0

Views: 973

Answers (2)

astax
astax

Reputation: 1767

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.

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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.)

Upvotes: 6

Related Questions