5 ms·
I was also thinking this while reading this (and I am very new to Go). Here's how I would write this in Go: https://gist.github.com/amix/9517995 https://gist.g
by amix 13y ago
I was also thinking this while reading this (and I am very new to Go). Here's how I would write this in Go:
https://gist.github.com/amix/9517995 https://gist.github.com/amix/9517995
I think this is the idiomatic way to implement this. It will lock the account every time you try to deposit to it (so other goroutines can't do it).
- xkarga00 13y agoUsing mutexes isn't considered as idiomatic Go code
- nkozyra 13y agoWell anything other than direct channel <-> goroutine is not considered idiomatic.
- zaphar 13y agoMutexes are absolutely idiomatic Go code. In fact the Core developers on the ML will often suggest them as a simplification over goroutines for synchronizing access to a shared resource. I'm not sure where you get the idea that they aren't idiomatic.
- xkarga00 13y agoProbably by making the mistake to read the Effective Go. http://golang.org/doc/effective_go.html#concurrency http://golang.org/doc/effective_go.html#concurrency "Do not communicate by sharing memory; instead, share memory by communicating. This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance. But as a high-level approach, using channels to control access makes it easier to write clear, correct programs. "
- amix 13y agoI don't really think what I suggest goes against the article you link to. It basically says: use channels when appropriate, but sometimes the best approach is to use locks. E.g. An bank account is shared state (similar to a reference count) and the best approach is to put a mutex around it instead of fighting with channel synchronization.
- xkarga00 13y agoThere are no implications here, it's stated pretty explicitly: "Reference counts MAY be best done by putting a mutex around an integer variable, for instance. BUT as a high-level approach, using channels to control access makes it easier to write clear, correct programs." There is a difference between what someone with a background from other mainstream programming languages might think would be the best approach to locking (mutexes) and the idiomatic Go approach (unbuffered channels).