Ios/os x Thread Safety Basics

Source: Internet
Author: User
<span id="Label3"></p><p><p>Dealing with multiple concurrency and reentrant issues is one of the more difficult challenges in each Library's development process. On the parse platform, we do our best to ensure that the actions you make when using my SDKs are thread-safe and that there is no performance problem.</p></p><p><p>In this article we will review some basic concepts on how to deal with multiple concurrency and competitive conditions in a concise, safe and clean manner.</p></p><p><p>first, before we go into the detail discussion, we define the following concepts:</p></p> <ul class=" list-paddingleft-2"> <ul class=" list-paddingleft-2"> <li><p><strong>thread</strong> : It is a context program executed by the operating system and can have multiple threads at the same time.</p></li> <li><p><strong>concurrency</strong> : a phenomenon in which multiple threads share the same resource while the program is Running.</p></li> <li><p><strong>reentrant</strong> : Through explicit recursion, software/hardware interrupts, or other methods, you can re-enter the function in the execution state of the Current.</p></li> <li><p><strong>atomicity of Operations</strong> : a property that guarantees the completion or failure of an operation, which never produces an intermediate state or an invalid State.</p></li> <li><p><strong>Thread Safety</strong> : A function that is thread-safe means that it does not produce an invalid state, cannot be observed, and cannot enter a concurrency State.</p></li> <li><p>reentrant <strong>style</strong> : If a function is reentrant, it means that it does not produce an invalid state, cannot be observed, and cannot enter a concurrency State.</p></li> </ul> </ul><p><p><strong>talking about thread safety The first thing that we often discuss is that thread safety is inherently difficult to Achieve. </strong>thread-related issues are difficult to document and repair because of the complex work of thread scheduling, memory garbage collection, cache errors, Branch predictions, and so On. Because of these factors, whenever possible, do not write code that could fall into a multithreaded Environment. If you follow the guidelines below, it can be quite easy to avoid a multithreaded environment:</p></p> <ul class=" list-paddingleft-2"> <ul class=" list-paddingleft-2"> <li><p>If possible, do not have a mutable state.</p></li> <li><p>Your code has a race condition.</p></li> <li><p>Use thread-local storage instead of global state when necessary.</p></li> <li><p>When confused, use the thread lock.</p></li> <li><p>finally, Make sure your code is competitive (although you think That's impossible).</p></li> </ul> </ul><p><p><strong>Competitive conditions</strong></p></p><p><p>Competitive state is the bane of multi-threaded System. How can you ensure that the order in which things happen is consistent with your expectations when you do not directly control the scheduling (such as what happens in a single thread)? There's a lot of good advice on how to track race conditions on the web, but There's very little about how to avoid them.</p></p><p><p>Most competitive states are caused by a shared mutable state, such as the following cases:</p></p><pre class="brush:js;toolbar:false"><pre class="brush:js;toolbar:false">void Thread1 () {_sharedstate = 1;    Do stuff if (somecondition) {_sharedstate = 0; }//do Stuff _sharedstate = 1;}    void Thread2 () {//do stuff if (_sharedstate = = 0) {_sharedstate = 1; }//do stuff}</pre></pre><p><p>If the value of the somecondition variable for thread 1 is true, is the value of _sharestate 0 or 1? This depends on the state of thread 2, regardless of whether thread 1 has the condition and the specified Value.</p></p><p><p>A mutable state does not necessarily imply a variable. States that include file systems, networks, system calls, and so on may be changed outside of your Application.</p></p><p><p><strong>States and Copying</strong></p></p><p><p>One of the best ways to avoid mutable states is to have a strict guideline on how to manage the state as a whole. In the parse library, let's stick to three rules:</p></p> <ol class=" list-paddingleft-2"> <ol class=" list-paddingleft-2"> <li><p>Separate the state from the code that can change the State. This allows you to separate reading from the focus of state mutation and allow you to implement better logic in your Thread's Code.</p></li> <li><p>Pass any object through mutable copy. Passing objects by reference can cause changes in concurrent resources, and in order to prevent this from happening, you need some sort of resource Synchronization.</p></li> <li><p>Use the thread lock (lock) whenever you encounter a time of confusion. this may slow down the application, but it is better than the case where the application crashes in the 1000 chosen competitive Environment.</p></li> </ol> </ol><p><p>Keep in mind that the global state is bad (including Singleton) and avoid using it as much as Possible. In the parse library, we prefer to use dependency injection (also called control Inversion) design patterns rather than singleton (for Example:-initwithobjectcontroller:vs [objectcontroller sharecontroller]), The reason for this is that it helps us keep track of the usage of objects, but also strengthens our ability to infer threads, and, if necessary, can use local thread storage instead of global Variables.</p></p><p><p>As mentioned above, a mutable state (as well as a global variable) makes handling concurrency more Difficult. So do whatever it takes to avoid it.</p></p><p><p><strong>Atomic Nature</strong></p></p><p><p>As stated above, the definition of atomicity is as Follows:</p></p><p><p>A property that guarantees the completion or failure of the operation, which never produces an intermediate state or an invalid State.</p></p><p><p>This definition looks mysterious and a bit difficult to understand. But what does it mean in practice?</p></p><p><p>If you have a count variable y, it needs to be updated in multiple threads. The naïve way to solve this problem is to let y increase directly, for example y++. however, there is an important flaw in this approach: what to do if there are two threads that increase y at the same time. This will force you to find alternative solutions.</p></p><p><p>One solution is to attach a lock on the count variable, but this will significantly degrade performance. Another solution (depending on the Situation) might be to use each sub-counter on each individual thread, but this increases the memory usage and cognitive load of the Program.</p></p><p><p>But there are better ways to do it. With some special instructions for the indicator, these instructions are separated from the function, and they can ensure that all operations on a memory address are synchronized correctly. These actions are emitted by the indicator, not by the system Operation. The basic theory of creating a Lock-free data structure is practical, but not in the scope of this Article.</p></p><p><p>In general, if you operate on a given address that is atomic, it is not possible to invalidate your application without reading that address. Once these parameters are combined with the atomicity attribute, it is ensured that a single parameter cannot be in an invalid State. Note that objects as a whole may still be in an invalid state because the performance of each atomic operation is completely independent of the other atomic operations that are being performed on the other memory Addresses.</p></p><p><p><strong>Lock</strong></p></p><p><p>When atomicity does not satisfy your purpose, you do have a lot of traditional ways of locking in thread Safety. There are many forms of lock, the problem is to find in many forms the best way to solve many contradictions rebirth Predicament. Below we will discuss some of the default scenarios in Ios/os.</p></p><p><p>Before we talk about locks, we first need to know when to Lock. One of the biggest mistakes in Thread-safe development is the easy use of locks. of course, If you lock every method of invoking an object, it is impossible to have a competitive condition. however, If you are getting a mutable state, it is better to detach the state from the Thread.</p></p><p><p>below, we will show several types of locks, the following example begins</p></p><p><p>This simple function appears to be completely free of problems, but it is neither Thread-safe nor Reentrant. There are many problems with the user segment Code.</p></p><p><p>In the case of concurrent actual use, the operator *= is not atomic. This means that if there are two threads calling the Incrementfooby: method at the same time, we will eventually get an intermediate value, and it does not represent any valid State.</p></p><p><p>In the case of a reentrant actual use, if the multiplication and assignment in the above example caused an interruption, we would encounter a similar problem, that is, we would get a strange middle Value.</p></p><p><p>All the above code doesn't work and we need to make some changes to make it better.</p></p><p><p><strong>Method 1: Use @synchronized keyword</strong></p></p><p><p>This solves concurrency problems and reentrant problems, But it also creates several new Problems. first, It is clear that we have limited the synchronization of other threads to the object by synchronizing the object itself, and if this function is used in large numbers, there will be a bad Situation.</p></p><p><p>The second problem is brought by @synchronized, and for many weeks, the performance of @synchronized is Bad. however, in objective-c, It is one of the simplest ways to create a lock. This does not mean there is no better way to create a lock.</p></p><p><p><strong>Method 2: Serial Queue</strong></p></p><p><p>In a sense, in your Cocoa/cocoa touch programming career, You must be able to touch one of the serial queues, which is the main thread. A serial dispatch queue is a list of tasks that are executed in a linear manner, which are threads from the OS System. however, The scheduling queue has some unique features that make it more appropriate to create a lock than @synchronized.</p></p><p><p></p></p><pre class="brush:js;toolbar:false"><pre class="brush:js;toolbar:false">@implementation someobject () {dispatch_queue_t _barqueue;//= dispatch_queue_create ("com.parse.example.queue", dispatch_queue_serial);}    -(nsinteger) foo {__block nsinteger result = 0;    Dispatch_sync (_barqueue, ^{result = _foo;    }); Return result;}    -(void) incrementfooby: (nsinteger) x {dispatch_sync (_barqueue, ^{_foo + = x; });} @end</pre></pre><p><p></p></p> <ul class=" list-paddingleft-2"> <ul class=" list-paddingleft-2"> <li><p>In addition to the home row, all dispatch queues will ignore the signal interrupt, which makes the compound logic more obvious to re-enter the Resource.</p></li> <li><p>With their QoS systems, scheduling queues are not controlled by priority Inversion.</p></li> <li><p>You can set deferred execution without destroying the synchronization model.</p></li> </ul> </ul><p><p>however, when your resources are mutually exclusive, using a scheduling queue can have the following drawbacks, including:</p></p> <ul class=" list-paddingleft-2"> <ul class=" list-paddingleft-2"> <li><p>All dispatch queues are non-reentrant, which means that if you synchronize in the current queue, you will have a deadlock Situation.</p></li> <li><p>The dispatch queue object has a large memory capacity compared to a simple osspinlock, with a minimum of approximately 128 bytes (plus an extra space internal pointer), and Osspinlock only 4 bytes.</p></li> <li><p>Since the __block variable is required to receive, the Dispatch_sync block return value sometimes becomes a bit annoying.</p></li> <li><p>The serial queue does not handle the exception dispatch queue Well.</p></li> </ul> </ul><p><p>The tradeoff of these performance benefits in most scenarios is worthwhile and is widely used in the SDK.</p></p><p><p><strong>Method 3: Parallel queues</strong></p></p><p><p>Method 2 is good in a read-write balanced scenario (such as the same number of get and set methods). however, in real life, that situation is rarely seen. The situation you often encounter is to read a certain number of times, only occasionally to write Data.</p></p><p><p>Scheduling is built on the basis of supporting so-called read-write locks in the form of parallel columns. however, They work like most other queues, and they try to make it possible for more people to access dispatch_barrier blocks as much as they can. This allows the queue to run separately in the context of the parallel queue and helps us speed up use cases without competitive conditions.</p></p><pre class="brush:js;toolbar:false"><pre class="brush:js;toolbar:false">@implementation someobject () {dispatch_queue_t _barqueue;//= dispatch_queue_create ("com.parse.example.queue", Dispa tch_queue_concurrent);}    -(nsinteger) foo {__block nsinteger result = 0;    Dispatch_sync (_barqueue, ^{result = _foo;    }); Return result;}    -(void) incrementfooby: (nsinteger) x {dispatch_barrier_sync (_barqueue, ^{_foo + = x; });} @end</pre></pre><p><p>Another advantage of the above code is that it makes it clearer to us that those functions update instance variables, and those functions do Not.</p></p><p><p>It is important to know that the performance overhead of a parallel queue is much larger than the overhead of a serial Queue. In a competitive environment (such as multiple invocations of dispatch_barrier_sync), one obvious benchmark is a parallel queue</p></p><p><p>It takes more time to rotate the lock inside than a serial Queue.</p></p><p><p><strong>Conclusion</strong></p></p><p><p>In the parse library, we strive to create the best APIs interface, the best threading Support. We use a large number of mechanisms within this SDK for any mobile application and are the Best. Please continue to follow us and we will continue to post similar articles in the coming weeks. We will share more about testing concepts, knowledge and More.</p></p><p><p>All translations in this article are for learning and communication purposes only, Please specify the translator, source, and link to this Article.</p></p><p><p>Ios/os x Thread Safety Basics</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.