Reputation: 363
I'm reading the book "Concurrency in Go" now and this decision tree is designed for teaching us to choose "primitives" or "channels".
Is it a performance-critical section?
This absolutely does not mean, “I want my program to be performant, therefore I will only use mutexes.” Rather, if you have a section of your program that you have profiled, and it turns out to be a major bottleneck that is orders of magni‐ tude slower than the rest of the program, using memory access synchronization primitives may help this critical section perform under load. This is because channels use memory access synchronization to operate, therefore they can only be slower. Before we even consider this, however, a performance-critical section might be hinting that we need to restructure our program.
But it still not explain why we should use channels
, because performance
always matters so “I want my program to be performant, therefore I will only use mutexes.”
So I still do not know how to choose using mutexes or channels.
Upvotes: 0
Views: 1230
Reputation: 8395
The premise here of choosing between channel and mutex based on performance is a false dilemma.
Channels are more expensive because they do more. By going from channels to primitives, you are losing some functionality.
If your program still works correctly, that means you didn't need that additional functionality to begin with.
If your program doesn't work anymore, that means you need to "build back up" to the lost functionality.
Channels are very simple in concept and are built into the language and runtime itself (including various optimizations and tricks you don't have access to in user-land code). This means that, practically speaking, any attempt to "build back up" from primitives will result in a worse implementation than chan
.
Upvotes: 6