1. Some concepts
· Process: a running executable with independent virtual memory space and system resources. Contains one main thread and multiple child threads. If the main thread exits, the process terminates. · Thread: a separate, minimal code execution path. The iOS thread base is POSIX. · Task: a piece of code. · Difference between serial and parallel: the number of tasks allowed to be executed simultaneously. Serial execution of one task at a time, while parallel execution of multiple tasks at a time. · The difference between synchronous and asynchronous: whether the current thread is blocked. Synchronously blocked, waiting for the result of the previous task. Asynchronous does not block. · Queues and threads: serial queues execute one task at a time, while concurrent queues execute multiple tasks at the same time. IOS uses queues to schedule tasks. Threads are created and destroyed according to scheduling needs and the current load state of the system, without manual management of threads. In iOS, the system deals with threads, and we only need to define the tasks to be scheduled.Copy the code
2.GCD
· Sync: Blocks the current thread until the task in the block completes. · Async: does not block the current thread, new threads are opened · Serial queue: follows FIFOCopy the code
· Parallel queue
dispatch_queue_t queue = dispatch_get_main_queue();
Copy the code
2) Custom queue (serial, parallel)
// The second parameter DISPATCH_QUEUE_SERIAL or NULL is serial, Dispatch_queue_t queue = dispatch_queue_create(dispatch_queue_t queue = dispatch_queue_create("com.baidu.wk.testQueue", NULL);
Copy the code
3) Global parallel queues
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
Copy the code
2.3 Creating a Task 1) Synchronization task (no thread is enabled)
dispatch_sync(, ^{
//code here
NSLog(@"% @", [NSThread currentThread]);
});
Copy the code
2) Asynchronous thread (open thread)
dispatch_async(, ^{
//code here
NSLog(@"% @", [NSThread currentThread]);
});
Copy the code
2.4 Group Queue After multiple queues are added to a group, dispatch_group_create is sent
dispatch_group_async
dispatch_group_notify
//1. Create queue group dispatch_group_t group = dispatch_group_create(); Dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //3. Execute tasks using queue group methods multiple times, only asynchronous method //3.1. Execute 3 cycles dispatch_group_async(group, queue, ^{for (NSInteger i = 0; i < 3; i++) {
NSLog(@"group-01 - %@", [NSThread currentThread]); }}); Dispatch_group_async (group, dispatch_get_main_queue(), ^{for (NSInteger i = 0; i < 8; i++) {
NSLog(@"group-02 - %@", [NSThread currentThread]); }}); Execute 5 cycles dispatch_group_async(group, queue, ^{for (NSInteger i = 0; i < 5; i++) {
NSLog(@"group-03 - %@", [NSThread currentThread]); }}); //4. Dispatch_group_notify (group, dispatch_get_main_queue(), ^{NSLog(@)"Done - %@", [NSThread currentThread]);
});
Copy the code
2.5 Dispatch_after Is delayed
dispatch_after(dispatch_time_t when, dispatch_queue_t queue, ^{
});
Copy the code
2.6 Execute dispatch_after once. This mode is used in singleton design mode and is thread-safe. Performance is much higher than mutex, and Apple recommends it. 2.7 Inter-thread Communication Time-consuming operations are performed asynchronously in the global queue and the results are passed to the main thread for UI presentation
Dispatch_async (dispatch_get_global_queue(0,0), ^{dispatch_async(dispatch_get_main_queue(), ^{// update UI}); });Copy the code
- NSOperation NSOperation and NSOperationQueue correspond to GCD tasks and queues respectively. The steps are as follows: · The task to be executed is encapsulated in an NSOperation object. · Add this task to an NSOperationQueue object. · NSOperation is an abstract class, with subclasses NSInvocationOperation and NSBlockOperation, only asynchronous but not synchronous. · NSInvocationOperation: calls a selector; NSBlockOperation: Executes one or more blocks concurrently
- Adding a Task 3.1.1 NSInvocationOperation
NSInvocationOperation * Operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil]; //2. Start [operation start];Copy the code
3.1.2 NSBlockOperation
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@)"% @", [NSThread currentThread]); }]; //2. Start task [operation start];Copy the code
AddExecutionBlock: This method is used to add concurrent blocks to Operation that will execute these tasks on the main thread and on multiple other threads. Similar dispatch_group.
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@)"% @", [NSThread currentThread]); }]; // Add multiple blocksfor (NSInteger i = 0; i < 5; i++) {
[operation addExecutionBlock:^{
NSLog(@"%ld time: %@", i, [NSThread currentThread]); }]; } //2. Start task [operation start];Copy the code
To inherit the NSOperation class and implement its main() method, you also need to implement various methods, including cancel(). I haven’t used it yet. 3.2 to add tasks to a column addOperation: add an operation to the operation queue addOperations: waitUntiFinished: add a set of operations to the operation · addOperationWithBlock: Directly add a block to the operation Queue without creating an NSBlockOperation object. 1)
NSOperationQueue *queue = [NSOperationQueue mainQueue];
Copy the code
- Other queue
/1. Create another queue NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@)"% @", [NSThread currentThread]); }]; //3. Add multiple blocksfor (NSInteger i = 0; i < 5; i++) {
[operation addExecutionBlock:^{
NSLog(@"%ld time: %@", i, [NSThread currentThread]); }]; } //4. Queue addOperation:operation;Copy the code
3) set the maximum number of concurrent thinking about a problem, maxConcurrentOperationCount = 1 and the GCD serial execution is the same?
MaxConcurrentOperationCount > 1 is concurrent, = 1 is the effect of serial, but the execution order of operation is still the same will be affected by other factors, For example, the isReady state of operation and the queue priority of operation.
Therefore, a serial operation queue is essentially different from a serial Dispatch queue because the order of execution is always FIFO. If the order of operations is important to us, we should establish its dependencies before adding operations to the Operation Queue. 3.3 add dependent – addOperations: waitUntileFinished: this is asynchronous, follow-up after operation. -addDependency: dependency to compensate for the failure of NSOperation asynchronism to ensure the execution order. Interdependence leads to deadlocks. But it can be dependent across queues.
NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@)"Download picture - %@", [NSThread currentThread]); [NSThread sleepForTimeInterval: 1.0]; }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"Watermark - %@", [NSThread currentThread]); [NSThread sleepForTimeInterval: 1.0]; }]; NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{NSLog(@"Upload picture - %@", [NSThread currentThread]); [NSThread sleepForTimeInterval: 1.0]; }]; //4. Set dependency [operation2 addDependency:operation1]; // Task two depends on task one [operation3 addDependency:operation2]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperations:@[operation3, operation2, operation1]waitUntilFinished:NO];
Copy the code
3.4 Other Usage · NSOperation
BOOL executing; // Check whether the task is being executed BOOL FINISHED; Void (^completionBlock)(void); // Set the operation to be performed after completion - (void)cancel; // Cancel the task - (void)waitUntilFinished; // Block the current thread until the task completesCopy the code
· NSOperationQueue
NSUInteger operationCount; CancelAllOperations - (void)cancelAllOperations; // Unqueue all tasks - (void)waitUntilAllOperationsAreFinished; // Block the current thread until all tasks in this queue are completedsetSuspended:YES]; // pause queue [queuesetSuspended:NO]; / / continue to queueCopy the code
· Mutex: Adding a mutex to a block of code that needs to be synchronized ensures that only one thread can access the block at a time.
@synchronized(self) {// synchronized(self)Copy the code
· Synchronous execution: We can use the knowledge of multi-threading to add this code to a serial queue, thus realizing the concept of thread synchronization. Of course, GCD and NSOpretion can be used here
Dispatch_sync (queue, ^{NSInteger ticket = lastTicket; //GCD // dispatch_sync(queue, ^{NSInteger ticket = lastTicket; [NSThread sleepForTimeInterval: 0.1]; NSLog(@"%ld - %@",ticket, [NSThread currentThread]); ticket -= 1; lastTicket = ticket; }); //NSOperation & NSOperationQueue Global NSOperationQueue, all operations added to the same queue // 2. Set the queue maxConcurrentOperationCount to 1/3. If subsequent operations need the results in the Block, they need to call each operation'swaitUntilFinished: blocks the current thread until the current operation is complete.waitUntilFinished must be added to the queue after! NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSInteger ticket = lastTicket; [NSThread sleepForTimeInterval:1]; NSLog(@"%ld - %@",ticket, [NSThread currentThread]);
ticket -= 1;
lastTicket = ticket;
}];
[queue addOperation:operation];
[operation waitUntilFinished];
Copy the code
.Delay execution
[self performSelector:@selector(run:) withObject:@"abc"afterDelay:3]; Dispatch_after [NSTimer scheduledTimerWithTimeInterval: 3.0 target: self selector: @ the selector (run) the userInfo: @"abc" repeats:NO];
Copy the code
. Singleton mode
static id _instance;
+ (instancetype)sharedTool {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[Tool alloc] init];
});
return _instance;
Copy the code
NSOperation: encapsulation of GCD, object-oriented, OC, features: dependency between operations; Cancel an ongoing operation, suspend and resume operation queue, etc. NSOperationQueue supports KVO and monitors operation status, such as whether an operation isExecuted, finished, or cancelled. Set the priority; GCD: C language, lightweight, more efficient. One-time, group queue, delay.