0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 2
    "Don't communicate by sharing memory, share memory by communicating" https://stackoverflow.com/q/36391421/125816 – Sergio Tulentsev Jul 22 '21 at 12:28
  • See also https://en.wikipedia.org/wiki/Communicating_sequential_processes and https://stackoverflow.com/questions/39826692/what-are-channels-used-for – JimB Jul 22 '21 at 14:13

2 Answers2

6

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.)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
4

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.

astax
  • 1,769
  • 1
  • 14
  • 23