blob: 1b4e7d8e71defbf3e7ddf7c51e615cf090cbcc94 [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001# Use a sync.Mutex or a channel?
2
3One of Go's mottos is _"Share memory by communicating, don't communicate by sharing memory."_
4
5That said, Go does provide traditional locking mechanisms in the <a href='http://golang.org/pkg/sync/'>sync package</a>. Most locking issues can be solved using either channels or traditional locks.
6
7So which should you use?
8
9Use whichever is most expressive and/or most simple.
10
11A common Go newbie mistake is to over-use channels and goroutines just because it's possible, and/or because it's fun. Don't be afraid to use a <a href='http://golang.org/pkg/sync/#Mutex'><code>sync.Mutex</code></a> if that fits your problem best. Go is pragmatic in letting you use the tools that solve your problem best and not forcing you into one style of code.
12
13As a general guide, though:
14
15| **Channel** | **Mutex**|
Dave Day682cb022014-12-10 15:32:04 +110016|:------------|:---------|
Andrew Gerrand5bc444d2014-12-10 11:35:11 +110017| passing ownership of data,<br />distributing units of work,<br /> communicating async results | caches,<br />state |
18
19If you ever find your sync.Mutex locking rules are getting too complex, ask yourself whether using channel(s) might be simpler.
20
21## More Info
22
23 * Channels in Effective Go: http://golang.org/doc/effective_go.html#channels
Dave Day682cb022014-12-10 15:32:04 +110024 * The sync package: http://golang.org/pkg/sync/