Deep understanding of locks in IOS development

Source: Internet
Author: User
<span id="Label3"></p>Deep understanding of lock summaries in IOS development<p><p>The purpose of this article is not to introduce how to use the various locks in ios, on the one hand, the author does not have a lot of actual combat experience, on the other hand such articles quite a lot, such as iOS to ensure that several ways of thread safety and performance comparison, iOS common knowledge points (three): Lock. This article will not detail the specific implementation of the principle of the lock, which will involve too much relevant knowledge, I dare not fraught.</p></p><p><p>This article is to do is a simple analysis of the IOS development of several common locks how to achieve, and what the pros and cons are, why there is a performance gap, will eventually simply introduce the underlying implementation of the lock Principle. The level is limited, if careless mistake, Welcome to communicate Correct. At the same time, readers are advised to have a general understanding of how to use the various locks in OC before reading this article.</p></p><p><p>In Ibireme's no longer secure Osspinlock article, There is a picture that simply compares the unlocking performance of various locks:</p></p><br>Source: Ibireme<p><p>This article analyzes the implementation of each lock in order from top to bottom (fast to slow). It should be noted that the addition of the lock speed does not indicate the efficiency of the lock, only to indicate the complexity of the implementation of the unlock operation, the following will be explained by specific Examples.</p></p>Osspinlock<p><p>The above article has described the Osspinlock is no longer secure, the main reason is that when a low-priority thread gets a lock, the high-priority thread enters the busy (busy-wait) state, consumes a lot of CPU time, which causes the low-priority thread to get no CPU time, and cannot complete the task and release the LOCK. This problem is called priority Reversal.</p></p><p><p>Why does a busy wait cause a low-priority thread to get no time slices? This has to be said from the operating System's thread scheduling.</p></p><p><p>Modern operating systems typically employ a time-slice rotation algorithm (Round Robin, or RR) when managing common THREADS. Each thread is allocated a time slice (quantum), usually around 10-100 milliseconds. When a thread runs out of its own time slice, it is suspended by the operating system and placed in the waiting queue until the next time slice is Allocated.</p></p>Principle of spin lock implementation<p><p>The purpose of the spin lock is to ensure that only one thread in the critical section can be accessed, and its use can be described by the following pseudo-code:</p></p><pre><pre><span style="color: #0000ff"></span> do <span style="color: #000000">{ Acquire lock Critical</span>section<span style="color: #008000">//</span> <span style="color: #008000"> critical area</span> <span style="color: #000000"> Release Lock </span><span style="color: #008000">/ /</span> <span style="color: #008000"> code that does not require lock protection</span> }</pre></pre><p><p>In the acquire lock step, we apply for lock-in to protect the code in the critical area (Critical Section) from being executed by multiple threads.</p></p><p><p>The idea of a spin lock is simple, theoretically, as long as a global variable is defined to represent the availability of the lock, the pseudo-code is as Follows:</p></p><pre><span style="color: #0000ff"><span style="color: #0000ff">BOOL</span></span> <span style="color: #0000ff"><span style="color: #0000ff">Lock</span></span>=<span style="color: #0000ff"><span style="color: #0000ff">false</span></span>;<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">there is no lock at the beginning, and any thread can apply for locks</span></span><span style="color: #0000ff"><span style="color: #0000ff"></span> do</span><span style="color: #000000"><span style="color: #000000"> { </span></span><span style="color: #0000ff"><span style="color: #0000ff"></span> while</span>(<span style="color: #0000ff"><span style="color: #0000ff">Lock</span></span>);<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">If lock is true, the loop is always dead, which is equivalent to requesting a lock</span></span> <span style="color: #0000ff"><span style="color: #0000ff">Lock</span></span>=<span style="color: #0000ff"><span style="color: #0000ff">true</span></span>;<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000">locked <span style="color: #008000">so that no other thread can get the lock</span></span>Critical section<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">critical Section</span></span> <span style="color: #0000ff"><span style="color: #0000ff">Lock</span></span>=<span style="color: #0000ff"><span style="color: #0000ff">false</span></span>;<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">equivalent to releasing the lock so that other threads can enter the critical section</span></span>Reminder section<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">code that does not require lock protection</span></span>}</pre><p><p>The comments are clearly written and are no longer analyzed on a line-by-row basis. unfortunately, There is a problem with this code: if there are multiple threads executing the while loop at the beginning, they will not be stuck here, but will continue to execute, so that the reliability of the lock is not guaranteed. The solution is also very simple, as long as the process of ensuring the application of the lock is atomic Operation.</p></p>Atomic operation<p><p>The atomic operation in the narrow sense represents a non-disruptive operation, which means that the thread will not be suspended by the operating system during the execution of the operation, but must be executed. In a single-processor environment, an assembly instruction is obviously atomic, because interrupts are also implemented through Directives.</p></p><p><p>In the case of multiprocessor, however, operations that can be performed concurrently by multiple processors are not counted as atomic operations. therefore, the real atomic operation must be supported by the hardware, such as the x86 platform if the command before the "lock" prefix, the corresponding machine code in the execution of the bus lock, so that the other CPUs can no longer perform the same operation, from the hardware level to ensure the atomicity of the Operation.</p></p><p><p>These very low-level concepts do not need to be fully mastered, as long as we know that the process of applying for locks can be done with an atomic operation <code>test_and_set</code> , which can be expressed in pseudo-code:</p></p><pre><pre><span style="color: #0000ff">bool</span> test_and_set (<span style="color: #0000ff">bool</span> *<span style="color: #000000">target) { </span><span style="color: #0000ff">bool</span> RV = *<span style="color: #000000">target; </span> *target =<span style="color: #000000"> TRUE; </span> <span style="color: #0000ff">return</span> <span style="color: #000000">rv;}</span></pre></pre><p><p>The purpose of this code is to set the target value to 1 and return the original Value. of course, in a concrete implementation, it is done by an atomic Directive.</p></p>Summary of Spin Lock<p><p>At this point, the principle of the spin lock is very clear:</p></p><pre><pre> <span style="color: #0000ff">bool </span> <span style="color: #0000ff">lock </span> = <span style="color: #0000ff">false </span>; <span style="color: #008000">//</span> <span style="color: #008000" and any thread can request a lock at the beginning without locking < span> <span style="color: #0000ff">do </span> <span style="color: #000000"> {</span> <span style="color: #0000ff">while </span> (test_and_set (&<span style=" Color: #0000ff ">lock </span>); <span style="color: #008000">//</span> <span style="color: #008000"> Test_and_set is an atomic operation </span> Critical section <span style="color: #008000">//</span> <span style="color: #008000" "critical section < span> <span style=" color: #0000ff ">lock </span> = <span style=" color: #0000ff ">false </span>; <span style="color: #008000">//</span> <span style="color: #008000" is equivalent to releasing the lock so that other threads can enter critical section < span> Reminder section <span style="color: #008000">//</span> <span style="color: #008000"> Code that does not require lock protection </span>} </span></span></span></pre></pre><p><p>It is not a good idea to use a spin lock if the critical section takes too long to Execute. Before we introduced the time slice rotation algorithm, the thread would exit its own time slice in many Cases. One of them is to run out of time slices and be forced to preempt by the operating System. In addition, when a thread makes an I/O operation, or goes to sleep, it will voluntarily make a time slice. Obviously in the while loop, the thread is in a busy state, wasting CPU time, and finally because the time-out is the operating system to seize the Times slice. If the critical section executes for a long time, such as file reading and writing, this kind of busy is unnecessary.</p></p>Signal Volume<p><p>Before I introduced the GCD bottom implementation of the article briefly describes the implementation principle of the semaphore <code>dispatch_semaphore_t</code> , it will eventually call to the <code>sem_wait</code> method, this method is implemented in the GLIBC as Follows:</p></p><pre><pre> <span style="color: #0000ff">int </span> sem_wait (sem_t *<span style="color: #000000">sem) {</span> <span style="color: #0000ff">int </span> *futex = (<span style="color: #0000ff">int </span> *<span style="color: #000000" ) sem; < span> <span style="color: #0000ff">if </span> (atomic_decrement_if_positive (futex) > <span style="color: #800080">0 </span> <span style="color: #000000">) </span> <span style="color: #0000ff">return </span> <span style="color: #800080">0 </span> <span style="color: #000000">; </span> <span style="color: #0000ff">int </span> err = lll_futex_wait (futex, <span style="color: #800080">0 </span> Span style= "color: #000000"); </span> <span style="color: #0000ff">return </span>-<span style="color: #800080">1 </span> <span style="color: #000000">;) </span> </pre></pre><p><p>first, the value of the semaphore is reduced by one and the number is judged to be greater than 0. If it is greater than 0, the description does not wait, so return immediately. The specific wait operation <code>lll_futex_wait</code> is implemented in the function, and LLL is the abbreviation for the low level LOCK. This function through the assembly code implementation, call to <code>SYS_futex</code> this system call, so that the thread into the sleep state, actively let out the time slice, this function in the implementation of the mutex, it is also possible to be used.</p></p><p><p>Unsolicited time slices do not always represent high efficiency. Making a time slice can cause the operating system to switch to another thread, which typically takes about 10 microseconds and requires at least two switching. If the wait time is short, such as only a few microseconds, busy waiting is more efficient than thread Sleep.</p></p><p><p>As you can see, the implementation of the spin lock and the semaphore is very simple, which is the reason why the two lock-up time is ranked first and second respectively. again, It is not possible to accurately reflect the efficiency of the lock (such as Time-slice switching), which can only measure the complexity of the lock to a certain extent.</p></p>Pthread_mutex<p><p>Pthread represents the POSIX thread, which defines a set of Cross-platform thread-related Api,pthread_mutex that represent Mutexes. Mutexes are implemented in very similar terms to semaphores, instead of using busy and so on, instead of blocking threads and sleeping, which requires context Switching.</p></p><p><p>Common uses for mutexes are as Follows:</p></p><pre><pre> <span style="color: #000000">pthread_mutexattr_t attr;pthread_mutexattr_init (</span> &<span style="color : #000000 ">attr");p thread_mutexattr_settype (</span> &attr, pthread_mutex_normal); <span style="color: #008000">//</span> <span style="color: #008000"> Defines the properties of a lock </span> <span style="color: #000000">pthread_mutex_t mutex;pthread_mutex_init (</span> &mutex, &attr) <span style=" Color: #008000 ">//</span> <span style=" color: #008000 "> Create lock </span> <span style=" color: #000000 ">pthread_mutex_lock (</span> &mutex); <span style="color: #008000">//</span> <span style="color: #008000"> request lock </span> <span style="color: #008000">//</span> <span style="color: #008000"> critical section </span> Pthread_mutex_unlock (&mutex); <span style="color: #008000">//</span> <span style="color: #008000"> release lock </span> </pre></pre><p><p>For pthread_mutex, it's usage and not much change before, the more important is the type of lock, can have, <code>PTHREAD_MUTEX_NORMAL</code> <code>PTHREAD_MUTEX_ERRORCHECK</code> and <code>PTHREAD_MUTEX_RECURSIVE</code> so on, the specific characteristics do not explain, there are a lot of relevant information on the INTERNET.</p></p><p><p>In general, a thread can only request one lock at a time, and can only release a lock if the lock is acquired, and multiple requests for a lock or release of an acquired lock can cause a Crash. Assuming that the lock has been acquired again, the thread will go to sleep because it waits for the lock to release, so it is impossible to release the lock again, resulting in a deadlock.</p></p><p><p>This often happens, for example, when a function requests a lock and then recursively invokes itself in the critical Section. Hurrily is to <code>pthread_mutex</code> support recursive lock, that is, allow a thread recursive application of the lock, as long as the type of attr <code>PTHREAD_MUTEX_RECURSIVE</code> can be changed.</p></p>Implementation of mutual exclusion lock<p><p>When a mutex is applied for a lock, the method is called, <code>pthread_mutex_lock</code> it is implemented on different systems, and sometimes its interior is implemented using semaphores, even without the semaphore, it is called to the <code>lll_futex_wait</code> function, which causes the thread to Hibernate.</p></p><p><p>As mentioned above, if the critical section is short, the efficiency of the busy wait may be higher, so in some versions of the implementation, a certain number of test_and_test (such as 1000 times) will be attempted first, which can improve performance when the mutex is used Incorrectly.</p></p><p><p>In addition, because <code>pthread_mutex</code> there are many types, can support recursive lock, etc., so when applying for lock, you need to judge the type of lock, which is why it is similar to the implementation of the semaphore, but the reason for a slightly lower efficiency.</p></p>Nslock<p><p>Nslock is a kind of lock that Objective-c exposes to the developer in the form of an object, its implementation is very simple, through the macro, defines the <code>lock</code> method:</p></p><pre><pre><span style="color: #0000ff">#define</span> MLOCK-(<span style="color: #0000ff">void</span><span style="color: #0000ff">lock</span><span style="color: #000000">{ </span><span style="color: #0000ff">int</span> err = pthread_mutex_lock (&<span style="color: #000000">_mutex); </span> <span style="color: #008000">//</span> <span style="color: #008000">Error Handling</span>...}</pre></pre><p><p><code>NSLock</code>Just inside the encapsulated one <code>pthread_mutex</code> , the property is <code>PTHREAD_MUTEX_ERRORCHECK</code> , it will lose a certain performance in exchange for error hints.</p></p><p><p>The reason for using a macro definition here is that there are several other locks inside OC, and their lock methods are identical, only the types of the internal <code>pthread_mutex</code> mutexes are Different. With macro definitions, You can simplify the definition of a method.</p></p><p><p><code>NSLock</code><code>pthread_mutex</code>The reason for this is that it requires a method call, and because of the presence of the cache, multiple method calls do not have much effect on performance.</p></p>Nscondition<p><p><code>NSCondition</code>The bottom layer is implemented by the conditional variable (condition variable) <code>pthread_cond_t</code> . A condition variable is a bit like a semaphore that provides a thread blocking and signaling mechanism, so it can be used to block a thread and wait for some data to be ready and then wake up the thread, such as a common Producer-consumer pattern.</p></p>How to use condition variables<p><p>Many <code>pthread_cond_t</code> of the articles mentioned here will need to be used in conjunction with mutex Locks:</p></p><pre><span style="color: #0000ff"><span style="color: #0000ff">void</span></span>Consumer () {<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">Consumer</span></span>Pthread_mutex_lock (&<span style="color: #000000"><span style="color: #000000">mutex); </span></span><span style="color: #0000ff"><span style="color: #0000ff"></span> while</span>(data = =<span style="color: #000000"><span style="color: #000000">NULL) {pthread_cond_wait (</span></span>&condition_variable_signal, &mutex);<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">Waiting for Data</span></span><span style="color: #000000"><span style="color: #000000"> } </span></span><span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">---have New data, The following code is responsible for handling ↓↓↓↓↓↓</span></span><span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">temp = data; </span></span><span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">---have New data, The above code is responsible for processing ↑↑↑↑↑↑</span></span>Pthread_mutex_unlock (&<span style="color: #000000"><span style="color: #000000">mutex);}</span></span><span style="color: #0000ff"><span style="color: #0000ff">void</span></span><span style="color: #000000"><span style="color: #000000">producer () {pthread_mutex_lock (</span></span>&<span style="color: #000000"><span style="color: #000000">mutex); </span></span><span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">Production Data</span></span>Pthread_cond_signal (&condition_variable_signal);<span style="color: #008000"><span style="color: #008000">//</span></span><span style="color: #008000"><span style="color: #008000">send a signal to the consumer and tell them that they have new data</span></span>Pthread_mutex_unlock (&<span style="color: #000000"><span style="color: #000000">mutex);}</span></span></pre><p><p>naturally, we will have a question: "if you do not use the mutex, only the condition variable what is the problem?" ”。 The problem is that <code>temp = data;</code> this code is not thread-safe, and maybe there are other threads that have modified the data before you read it Out. So we need to make sure that the data that consumers get is thread-safe.</p></p><p><p>The wait method, in addition to being awakened by the signal method, can sometimes be woken up by a false, so it is necessary to make two confirmations of the judgment in the while Loop.</p></p>Why use conditional variables<p><p>There are many articles about condition variables, but most of them are silent on one basic question: "why use conditional variables?" It only controls the order in which threads are executed, can you simulate a similar effect with semaphores or mutexes? ”</p></p><p><p>The information on the Internet is relatively small, I briefly say a personal view. The semaphore can replace condition to some extent, but the mutex is Not. In the code of the Producer-consumer pattern given above, the essence of the method is the transfer of the lock, the <code>pthread_cond_wait</code> consumer abandons the lock, and then the producer obtains the lock, in the same way that <code>pthread_cond_signal</code> a lock is transferred from the producer to the Consumer.</p></p><p><p>If we use mutexes, we need to change the code to This:</p></p><pre><pre><span style="color: #0000ff">void</span> <span style="color: #008000">//</span> <span style="color: #008000">Consumer</span> Pthread_mutex_lock (&<span style="color: #000000">mutex); </span> <span style="color: #0000ff"></span> while (data = =<span style="color: #000000"> NULL) { pthread_mutex_unlock (</span>&<span style="color: #000000">mutex); Pthread_mutex_lock (</span>&another_lock) <span style="color: #008000">//</span> <span style="color: #008000"> equals wait another mutex</span> Pthread_mutex_lock ( &<span style="color: #000000">mutex); } Pthread_mutex_unlock (</span>&<span style="color: #000000">mutex);}</span></pre></pre><p><p>The problem with this is that, before waiting for another_lock, it is possible for the producer to execute the code before releasing the Another_lock. That is, there is no guarantee that releasing the lock and waiting for another lock are atomic, and there is no guarantee of the "wait first, release another_lock" order.</p></p><p><p>There is no problem with semaphores, because the wait and wake of semaphores do not need to be prioritized, and semaphores represent only how many resources are available, so there is no such problem. However <code>pthread_cond_wait</code> , there appears to be a risk of using semaphores compared to guaranteed atomic lock transfers (there is no problem with non-atomic operations for the time being).</p></p><p><p>however, using condition has a benefit that we can invoke <code>pthread_cond_broadcast</code> methods to notify all waiting consumers, which is not possible with Semaphores.</p></p>Nscondition's approach<p><p><code>NSCondition</code>In fact, it encapsulates a mutex and a conditional variable, and it exposes the former <code>lock</code> method and the latter to the <code>wait/signal</code> <code>NSCondition</code> object, exposing it to the user:</p></p><pre><pre>-(<span style="color: #0000ff">void</span><span style="color: #000000">) signal { pthread_cond_signal (</span>&<span style="color: #000000">_condition);}</span> <span style="color: #008000">//</span> <span style="color: #008000">in fact, This function is defined by a macro, which is how it is expanded</span> -(<span style="color: #0000ff">void</span><span style="color: #0000ff">lock</span> <span style="color: #000000"> { </span><span style="color: #0000ff">int</span> err = Pthread_mutex_lock (&<span style="color: #000000">_mutex);}</span></pre></pre><p><p>Its unlocking process is <code>NSLock</code> almost consistent, and theoretically time-consuming should be the same (and so is the actual test). It takes a little longer to show up in the diagram, and I guess it's possible that the tester has initialized and destroyed the variables before and after each additional unlock.</p></p>Nsrecursivelock<p><p>As mentioned above, recursive locks are also <code>pthread_mutex_lock</code> implemented by functions, in which the type of lock is judged, and if the display is a recursive lock, recursive calls are allowed, only one counter is added, and the release process of the lock is the Same.</p></p><p><p><code>NSRecursiveLock</code>The difference is that the type of the object that is <code>NSLock</code> encapsulated internally is <code>pthread_mutex_t</code> different, and the former is of type <code>PTHREAD_MUTEX_RECURSIVE</code> .</p></p>Nsconditionlock<p><p><code>NSConditionLock</code>By virtue <code>NSCondition</code> of this, Its essence is a producer-consumer model. "condition is met" can be understood as a new content provided by the Producer. <code>NSConditionLock</code>internally holds an <code>NSCondition</code> object, as well as a <code>_condition_value</code> property, that is assigned to the property at initialization time:</p></p><pre class="hljs undefined"><pre class="hljs undefined"><code class="objc">// 简化版代码</code></pre></pre><pre><pre>-<span style="color: #000000"> (id) initwithcondition: (nsinteger) value { </span><span style="color: #0000ff">if</span> (nil! = (self =<span style="color: #000000"> [super init])) {</span><span style="color: #0000ff">n EW</span><span style="color: #000000">] </span>=<span style="color: #000000"> value; } </span> <span style="color: #0000ff">return</span> self <span style="color: #000000">;} Its Lockwhencondition method is actually the consumer method:</span>-(<span style="color: #0000ff">void</span><span style="color: #000000">) lockwhencondition: (nsinteger) value { </span> <span style="color: #0000ff">Lock</span> <span style="color: #000000">]; </span> <span style="color: #0000ff"></span> while (value! =<span style="color: #000000"> _condition_value) { [_condition wait]; }}</span></pre></pre><p><p>The corresponding <code>unlockWhenCondition</code> method is the producer, using the <code>broadcast</code> method to inform all Consumers:</p></p><pre><pre>-(<span style="color: #0000ff">void</span><span style="color: #000000">) unlockwithcondition: (nsinteger) value { </span>=<span style="color: #000000"> value; [_condition broadcast]; [_condition unlock];}</span></pre></pre>@synchronized<p><p>This is actually a OC level lock, mainly by sacrificing performance in order to be concise and readable in grammar.</p></p><p><p>We know that @synchronized need to be followed by an OC object, which actually uses the object as a Lock. This is accomplished by a hash table, where OC uses an array of mutexes at the bottom (which you can understand as a lock pool) and obtains the corresponding mutex by hashing the Object.</p></p><p><p></p></p><p><p>Deep understanding of locks in IOS development</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.