5 ms·
No. There are usually talking about 2 threads accessing the same code. Let's suppose we have an int, and want to add 2, we would do: 1. int i = sharedInt 2.
by Matt3o12_ 11y ago
No. There are usually talking about 2 threads accessing the same code.
Let's suppose we have an int, and want to add 2, we would do:
1. int i = sharedInt
2. i = i + 2
3. sharedInt = i
(that's what the compile actually does when you write sharedInt += 2).
If the runtime decides two stop the current thread on line 2 and lets the second one run all three lines, we would have a problem if I didn't use a mutex.
- hurin 11y agoYou can compile on x86 for atomic increments? (Go seems to support it https://golang.org/pkg/sync/atomic/ https://golang.org/pkg/sync/atomic/)
- Matt3o12_ 11y agoI don't know but I think so. I just wanted to give him an oversimplified example (you could also use any complicated computation). I'm not sure, though, if every compiler/interpreter makes use of them (what about VMs)?
- jzelinskie 11y agoThis is available only under certain architectures (x86 is one of them as you've noted), but I've also seen scenarios where the atomic increment instruction is actually slower than using a mutex. Don't consider this feature to be a magic bullet and always test your use cases! As for the parent discussion, usually a mutex is talking about the threading construct while a "lock service" is how you'd refer to something like etcd or zookeeper.
- hurin 11y agoHow could it be slower than a mutex? Is it from compiling all your increments to use LOCK? What exactly were you timing? That sounds really strange..
- YZF 11y agoMutexes are typically implemented over atomic instructions. So you'd do something like atomic compare/exchange to acquire the mutex and if there's no contention you got it. If there is contention you go to the OSes synchronization constructs which are typically much slower... An atomic increment should always be faster than acquiring a mutex and incrementing...
- bottled_poe 11y ago> No. There are usually talking about 2 threads accessing the same code. Don't you mean two threads accessing the same data? Mutexes are about data protection. This usually manifests as exclusive exectution of code, but it is not the purpose.