Recently the other books have been put down, mainly in the study of GCD. If it is to work, to my previous learning gcd, nsoperation and other knowledge has been enough to use, but learning and not only the knowledge to use it, to know it, and know the reason why, so that you can continue to improve their technical level.
This article focuses on http://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1 and iOS and OS X multithreading and memory management, And some other assorted books or blogs.
GCD has been available for a long time, based on GCD object-oriented multithreading technology Nsoperation also appeared for a long time, but not everyone understand GCD main content, Concurrency has always been tricky (although the afnetworking framework avoids a lot of the time when we write multithreaded code in a program, but I think any programmer with an idea will have an in-depth understanding of concurrent programming and will grasp it), which is like a sharp set of edges and corners to poke into Objective-c's smooth world.
Here, I will be four of the space to comb what I know and understand GCD.
The first to second article mainly explains what GCD is, what can be done, and will provide some code fragments I have written, and if necessary, there will be Medo.
The third and third article is mainly to learn some advanced GCD provides advanced functions, if the time is sufficient, I will try to display the text + code +medo.
If you are completely unfamiliar with GCD and block (code blocks), read this article first: http://www.raywenderlich.com/4295/ Multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial "Getting Started with gcd and multithreading on iOS"
Process: That is, a running application.
Thread: A complete execution path in a process. A process can have multiple threads, at least one thread, which is the main path. In iOS development, all UI-related interfaces must be updated in the main thread.
What is GCD?
Apple's official explanation: GCD is one of the techniques for performing tasks asynchronously. Typically, the thread management code described in the application is implemented in a centralized system, and the developer only needs to define the tasks to be performed and append them to the
In the appropriate dispatch queue, GCD can generate the necessary threads and plan to perform the task.
It has the following advantages:
-
- GCD can improve application responsiveness by putting extremely long-spent tasks into a background thread
- GCD provides an easy-to-use concurrency model, not just locks and threads, to help us avoid concurrency traps
- GCD has the potential to optimize your code with a higher-performance primitive in common patterns (such as Singleton) (a singleton Medo is provided later)
- Wait a minute
As in the following code snippet:
dispatch_queue_t queue = dispatch_queue_create ("cn.chutong.www", dispatch_queue_concurrent); Dispatch_async (queue, ^{ /** put some extremely time-consuming tasks in this execution * /Dispatch_async (Dispatch_get_main_queue (), ^{ /** Time-consuming task completed, get resources, update UI update UI can only be updated in the main thread ( * }); });
I created a queue of parallel queues and executed the time-consuming operations asynchronously, and when the time-consuming operation was done, I got the resources back to the main thread to update the UI, and outside of this block of blocks, the main thread was not blocked by time-consuming tasks and could handle other things smoothly.
Some of the terms of GCD
To understand GCD, familiarize yourself with several concepts related to threading and concurrency.
Serial (Serial) and concurrency (Concurrent)
The task serial means that at the same time, there is only one task being executed, that is, one task is executed before the next task is executed.
Task concurrency means that at the same time, more than one task is executed.
Synchronous (synchronous) and asynchronous (asynchronous)
Synchronization means that the task is performed in the current thread and does not have the ability to open a new thread.
Asynchronously, performs a task in a new thread, with the ability to open a new thread.
In GCD, these terms describe when a function is completed relative to another task that the function requires GCD to perform. A synchronization function is returned only after it has completed its scheduled task.
An asynchronous function, on the contrary, returns immediately, and the scheduled task is completed but not waiting for it to complete. Therefore, an asynchronous function does not block the current thread from executing the next function.
Critical area (Critical section)
Is that a piece of code can not be executed concurrently, that is, two threads cannot execute this code at the same time. This is common because the code is going to manipulate a shared resource, for example, if a variable can be accessed by a concurrent process, it is likely to deteriorate (its value is no longer trusted).
Deadlock (Deadlock)
A thread that stops waiting for things causes multiple threads to keep waiting for each other, which is a deadlock.
Two (and sometimes more) things-in most cases, threads-the so-called deadlocks mean that they are stuck and waiting for each other to complete or perform other operations. The first one cannot be completed because it is waiting for the second one to complete. But the second can't be done, because it's waiting for the first one to finish.
Code snippet:
-(void) viewdidload { [super viewdidload]; Dispatch_sync (Dispatch_get_main_queue (), ^{ NSLog (@ "111111"); }); NSLog (@ "222222"); }
Execute the above code, you will find no print, this is a deadlock, we prohibit in the main queue (iOS development, the home column is a serial queue), in the synchronous use of the main queue to perform tasks, in the same way, prohibit in the same synchronous serial queue, and then use the serial queue to synchronize the execution of tasks, Because it will cause a deadlock.
Code snippet:
-(void) viewdidload { [super viewdidload]; dispatch_queue_t queue = dispatch_queue_create ("cn.chutong.www", dispatch_queue_serial); Dispatch_sync (queue, ^{ NSLog (@ "111111"); Dispatch_sync (queue, ^{ NSLog (@ "22222"); }); NSLog (@ "3333333"); }); NSLog (@ "44444444");}
Will find that it just prints once and then creates a deadlock.
Threading security (thread safe)
Thread-Safe code can be safely called in multi-threaded or concurrent tasks without causing any problems (data corruption, crashes, etc.). Thread-Unsafe code can run in only one context at a time. An example of a thread-safe code is nsdictionary. You can use it in multiple threads at the same time without problems. On the other hand, nsmutabledictionary is not thread-safe and should guarantee that only one thread can access it at a time.
Context Switch
A context switch refers to the process of storing and resuming execution state when you switch between different threads in a single process. This process is common when writing multitasking applications, but it brings some extra overhead.
Concurrency and parallelism
Parallel requirements concurrency, but concurrency does not guarantee parallelism, on the computer operating system, the open thread is very performance, that is, in fact, in a parallel processing task, the open thread is capped, if the upper limit is 2, that is, each time the new thread opened 2, then there is a possibility of concurrency but not parallel situation.
Different parts of the concurrent code can be executed "synchronously". However, how this happens or whether it happens depends on the system. Multi-core devices execute multiple threads concurrently, but in order for a single-core device to do this, they must first run a thread, perform a context switch, and then run another thread or process. This usually happens quickly enough to give us the illusion of a concurrent execution, as shown in:
Queuing (queue)
Apple's official description of GCD: What developers do is define the tasks they want to perform and append them to the appropriate dispatch queue.
The source of this sentence is as follows:
Dispatch_async (queue, ^{ /** * The task you want to perform */ });
The source uses the block syntax "define the task you want to perform", "Append" by the Dispatch_async function to the "Dispatch queue" in the variable queue. Just so that the specified block can be executed in another thread.
GCD provides a dispatch queue to handle code blocks that manage the tasks that you provide to GCD and perform these tasks in FIFO (first in, in-order) sequence. This guarantees that the first task to be added to the queue will be the first task in the queue, and the second task to be added will start the second one, so that the end of the queue.
What is the Dispatch queue? Is the wait queue for processing, and the programmer uses APIs such as Dispatch_async to describe the processing to be performed in the block syntax and append it to the dispatch queue. The Dispatch queue is processed in the order in which they are appended.
All dispatch queues (dispatch queue) themselves are thread-safe, and you can access them in parallel from multiple threads. The advantages of GCD are obvious when you understand how the dispatch queue provides thread safety for different parts of your own code. The key to this is to choose the right type of dispatch queue and the correct dispatch function to submit your work.
In addition, there are two Dispatch queues mentioned earlier in this article when performing processing, one serial Dispatch queue waiting to be processed now, and the other concurrent Dispatch queue.
Serial Queue (Serial Dispatch queue)
The execution time of these tasks is controlled by GCD; the only thing that can be ensured is that GCD executes only one task at a time and executes in the order that we add to the queue.
The following code, when calling the Serialprintnumber method:
#import "ViewController.h" @interface Viewcontroller () @property (nonatomic, strong) dispatch_queue_t serialqueue;@ Property (Nonatomic, Strong) dispatch_queue_t Concurrentqueue; @end @implementation viewcontroller-(void) ViewDidLoad { [Super Viewdidload]; Self.serialqueue = Dispatch_queue_create ("cn.chutong.www", dispatch_queue_serial); Self.concurrentqueue = Dispatch_queue_create ("cn.chutong.www", dispatch_queue_concurrent); for (int i = 0; i <, i++) { [self serialprintnumber:i];} } /** * Asynchronous Serial queue * */-(void) Serialprintnumber: (int) number{ dispatch_async (self.serialqueue, ^{ NSLog (@ "%d %@ ", number, [Nsthread CurrentThread]); } /** * Asynchronous Parallel queue * */-(void) Concurrentprintnumber: (int) number{ dispatch_async (self.concurrentqueue, ^{ NSLog (@ "%d %@", number, [Nsthread CurrentThread]); } @end
You can see a print like this:
A new sub-thread has been opened, and the task is executed sequentially. First-in-order execution. Because you want to wait for the previous task to finish, that is, at the same time, only one task can be processed to begin processing the next task.
Concurrent queues (Concurrent Dispatch queue)
The tasks in the concurrent queue are guaranteed to be executed in the order in which they were added, but that is all guaranteed. Tasks can be done in any order, and you won't know when to start running the next task, or how many blocks are running at any one time. Again, it all depends on GCD.
Code snippet:
#import "ViewController.h" @interface Viewcontroller () @property (nonatomic, strong) dispatch_queue_t serialqueue;@ Property (Nonatomic, Strong) dispatch_queue_t Concurrentqueue; @end @implementation viewcontroller-(void) ViewDidLoad { [Super Viewdidload]; Self.serialqueue = Dispatch_queue_create ("cn.chutong.www", dispatch_queue_serial); Self.concurrentqueue = Dispatch_queue_create ("cn.chutong.www", dispatch_queue_concurrent); for (int i = 0; i <, i++) { [self concurrentprintnumber:i];} } /** * Asynchronous Serial queue * */-(void) Serialprintnumber: (int) number{ dispatch_async (self.serialqueue, ^{ NSLog (@ "%d %@ ", number, [Nsthread CurrentThread]); } /** * Asynchronous Parallel queue * */-(void) Concurrentprintnumber: (int) number{ dispatch_async (self.concurrentqueue, ^{ NSLog (@ "%d %@", number, [Nsthread CurrentThread]); } @end
Print:
As you can see, the task is no longer executed sequentially, with multiple threads open. At this point, we can clearly know that the so-called "parallel Execution" is the use of multiple threads to handle multiple tasks simultaneously, because the time required to complete the task is different, so the final time to complete the task is different.
Serial Dispatch The relationship between the queue and the Concurrent Dispatch queue and thread, such as:
iOS development: An in-depth understanding of GCD first article