Threading is one of the most difficult things when you do programming. Fortunately, in comparisons to another frameworks, the Apple’s SDK handles the problem exceptionally well. At least it is my impression.
All chunks of job are arranged into Blocks or Functions/Methods. I’d like to mention that the Blocks have ability to capture their surrounding state. They close variables around that are in scope at the time the block is declared that’s why we call them also Closures
Kind of jobs might be perform in the separate threads
Computation intensive jobs: When the thread uses entire processing capability of CPU. The reasonable maximum number of the threads is the number of CPU cores. By crating more threads we cause unnecessary switching of the context by the CPU, which takes some unit of time therefore it makes the calculation slower.
I/O intensive jobs: In that case we can trigger more threads than we have CPU cores and there is a formula how we can calculate how many thread is an optimal Threads = Cores / (1-Blocking Factor). Here the switch of CPU context itself does not impact much into performance, because the thread probably is waiting for a signal anyway.
Mutex and the data consistency
What makes threading difficult is the data consistency. Imagine the situation when there are two threads that have a pointer to the same array which suppose to contains unique items. Both threads can modify and read the array. Let’s say both of the threads want to append the same item at exactly the same time to this array. What they do is to check if the item already exists in the array so they iterate through the array for checking the item if it is a duplicate and if not both of them will append it.
The array will contains two the same items or even works the app will crash because the array might be mutated at the time the other threat iterate through it.
The solution is to use mutex for blocking threads in order to avoid override the data.
Another mechanism for syncing thread is semaphore, but you need to be aware of potential deadlock. Below you can see one
The current thread stops and wait for a signal that can not be send in this case, because we try to send it from the same thread which is stopped.
There is no good idea to handle threads from low level because it affect highly into development time of an application, whoever as all of us we are curious about everything, so I am going to show you how to do pthreading on iOS. Here is an example:
I do not clame that everyting on this webpage is correct. Feel free to contribute to this blog on GitHub