Why use channel for concurrency control? mutex seems better. #46306
Replies: 1 comment
-
You have the lock and unlock operations swapped around.
As I explained in the commit message:
I also followed the same pattern in moby/daemon/logger/loggerutils/logfile.go Lines 50 to 64 in a65c948 The excellent Rethinking Classical Concurrency Patterns talk goes into much greater depth on the subject. I highly recommend reading (or watching) it. It was my main source of inspiration for using channels when I overhauled the logging subsystem. While mutexes may be faster than channels in your particular microbenchmark today, that does not make them inherently "better" in all respects. Speed is not the only dimension to consider. Concurrent code with shared memory is very hard to get right. Case in point: your benchmark code contains a race condition. And so did the old logger code which used mutexes. Race conditions lead to wrong answers, and wrong answers are almost never useful. The fastest program known is one which exits immediately, but unless you are writing tl;dr channels are used for concurrency control because they make it easier to write correct concurrent code, without impacting performance nearly as much as microbenchmarks may suggest. |
Beta Was this translation helpful? Give feedback.
-
In sharedtemp.go, channel stfcState is used for concurrency control.
This channel is similar to using a mutex.
Why not use mutex for concurrency control? In my tests, Mutex performed better than channel.
Beta Was this translation helpful? Give feedback.
All reactions