Summarize what I know about the lock under iOS:
1. Mutual exclusion Lock
@synchronized, @synchronized block implicitly adds an exception-handling routine to protect the code. The processing routine releases the mutex automatically when the exception is thrown. This means that in order to use the @synchronized directive, you must enable exception handling in your code.
Nslock
Nsrecursivelock, recursive lock, can be used multiple times in a thread
Nsconditionlock, conditional lock, in fact, is also a mutex, similar to nscondition, but nscondition wait is awakened, may not really meet the conditions, need to check, for example:
[cocoaCondition lock];while (timeToDoWork <= 0) [cocoaCondition wait]; timeToDoWork--;
Spin lock is also an exclusive lock
Dispatch once can also be regarded as an exclusive lock, its efficiency is quite high; I read an article with a basic understanding, do not use memory barrier, mainly using branch prediction method, used to prompt the branch prediction errors before, to achieve the effect; it's more interesting. One problem is whether the dispatch once can be used as an exclusive execution of some blocks, and if efficiency is better
2. Signal Volume
DISPATCH_SEMAPHORE,GCD, but did not find POSIX and Mach, POSIX should be able to use, Mach is said to be a kernel-state
3. Spin Lock
Osspinlocklock
4. Read/write Lock
POSIX read-write Lock: refer to Https://github.com/otium/OTMRWLock
5. Distributed lock
Distributed lock (distributed lock) process-level locks that only report status and do not block processes. Nsdistributedlock is implemented using a file system. I don't have a concept at all.
No lock synchronization
1. Atomic variables
Atomic variables, that is, send FSB lock bus, hardware lock
Type __sync_fetch_and_add (type *ptr, type value);
Type __sync_fetch_and_sub (type *ptr, type value);
Type __sync_fetch_and_or (type *ptr, type value);
Type __sync_fetch_and_and (type *ptr, type value);
Type __sync_fetch_and_xor (type *ptr, type value);
Type __sync_fetch_and_nand (type *ptr, type value);
Type __sync_add_and_fetch (type *ptr, type value);
Type __sync_sub_and_fetch (type *ptr, type value);
Type __sync_or_and_fetch (type *ptr, type value);
Type __sync_and_and_fetch (type *ptr, type value);
Type __sync_xor_and_fetch (type *ptr, type value);
Type __sync_nand_and_fetch (type *ptr, type value);
This iOS also has a corresponding function, such as OSAtomicIncrement32, which is relatively efficient.
2. CAS
CAS is really lock-free, __sync_bool_compare_and_swap, thread-safe