4 ms·
In Go tutorials I almost never see anything about mutexes or how to be thread safe
by nerdbaggy 6y ago
In Go tutorials I almost never see anything about mutexes or how to be thread safe
- strken 6y agoGenerally the answer is to stick everything into a channel. This doesn't fix race conditions, but it does make it easier to write code. Want to query the db in parallel? Start n goroutines and write the results to a channel, then read from the channel n times. Want to limit your concurrency to m tasks? Start m goroutines reading tasks from a tasks channel and pushing results to a results channel, write n tasks to the tasks channel, read n results from the results channel.
- eknkc 6y agoI find the channels to be the most confusing thing in Go. What happens when you write to a closed channel? What about a blocked one? What if you read from a closed one. Can you close a closed channel? Does that panic? What was the non blocking read? What about write? Fuck that, I use the sync Mutex primitives and good old slices instead.
- Groxx 6y ago+1 to this. I'd say nearly half of the channel code I've encountered in "real code" has had severe flaws when things don't align perfectly. They don't have data races, in that the race detector will give it a thumbs-up, but they do have semantic races leading to deadlocks, misbehavior, dropped data, etc. They generally work fine when they're not under heavy load / contention, so they aren't noticed until they collapse. Mutex code though? 90% correct, easily. It's often dramatically simpler to make correct, especially when more than one construct is needed, or nearly anywhere with error handling. (`defer` is quite nice for locks)
- lanstin 6y agoCause you need not worry about the threading if you are using channels and go routines. The scheduler does it all f9r you - you just describe the data flow and the concurrency.
- erik_seaberg 6y agoSharing mutable state is still pretty risky; either immutable objects or byte channels (no pointers and no non-serialized objects) would have helped a lot.