1 Preface
This chapter introduces Apple's new method to simplify multithreading and become Grand Central Dispatch (GCD). It provides a new set of APIs, you can split the work that the application needs to execute into smaller blocks that can be distributed across multiple threads and CPUs, thus solving the user experience problem.
2. Details
2.1 simulate easy-to-use operations
Next, let's simulate this time-consuming operation to create a project. When you click Start Working, it will wait 10 seconds and then display the content, and output the time-consuming data in the console:
Code instance
ZYViewController. m
[Plain] //
// ZYViewController. m
// SlowWorker
//
// Created by zhangyuc on 13-6-7.
// Copyright (c) 2013 zhangyuc. All rights reserved.
//
# Import "ZYViewController. h"
@ Interface ZYViewController ()
@ End
@ Implementation ZYViewController
@ Synthesize startButton, resultsTextView;
-(NSString *) fechSomethingFromServer {
// Sleep the thread for 1 second
[NSThread sleepForTimeInterval: 1];
Return @ "Hi there ";
}
-(NSString *) processData :( NSString *) data {
[NSThread sleepForTimeInterval: 2];
// Uppercase Conversion
Return [data uppercaseString];
}
-(NSString *) caculateFirstResult :( NSString *) data {
[NSThread sleepForTimeInterval: 3];
// Obtain the length
Return [NSString stringWithFormat: @ "Number of chars: % d", [data length];
}
-(NSString *) caculateSenondResult :( NSString *) data {
[NSThread sleepForTimeInterval: 4];
// Replace "e" with "E"
Return [data stringByReplacingOccurrencesOfString: @ "E" withString: @ "e"];
}
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(Void) didReceiveMemoryWarning
{
[Super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(Void) dealloc {
[StartButton release];
[ResultsTextView release];
[Super dealloc];
}
-(IBAction) doWorking :( id) sender {
// Obtain the current time
NSDate * startTime = [NSDate date];
NSString * fetchedData = [self fechSomethingFromServer];
NSString * processedData = [self processData: fetchedData];
NSString * firstResult = [self caculateFirstResult: processedData];
NSString * secondResult = [self caculateSenondResult: processedData];
NSString * resultsSummary = [NSString stringWithFormat: @ "First: [% @] \ nSecond: [% @]", firstResult, secondResult];
// Assign a value to the text attribute of resultsTextView
ResultsTextView. text = resultsSummary;
NSDate * endTime = [NSDate date];
// Obtain the time difference in seconds.
NSLog (@ "Completed in % f seconds", [endTime timeIntervalSinceDate: startTime]);
}
@ End
//
// ZYViewController. m
// SlowWorker
//
// Created by zhangyuc on 13-6-7.
// Copyright (c) 2013 zhangyuc. All rights reserved.
//
# Import "ZYViewController. h"
@ Interface ZYViewController ()
@ End
@ Implementation ZYViewController
@ Synthesize startButton, resultsTextView;
-(NSString *) fechSomethingFromServer {
// Sleep the thread for 1 second
[NSThread sleepForTimeInterval: 1];
Return @ "Hi there ";
}
-(NSString *) processData :( NSString *) data {
[NSThread sleepForTimeInterval: 2];
// Uppercase Conversion
Return [data uppercaseString];
}
-(NSString *) caculateFirstResult :( NSString *) data {
[NSThread sleepForTimeInterval: 3];
// Obtain the length
Return [NSString stringWithFormat: @ "Number of chars: % d", [data length];
}
-(NSString *) caculateSenondResult :( NSString *) data {
[NSThread sleepForTimeInterval: 4];
// Replace "e" with "E"
Return [data stringByReplacingOccurrencesOfString: @ "E" withString: @ "e"];
}
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(Void) didReceiveMemoryWarning
{
[Super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(Void) dealloc {
[StartButton release];
[ResultsTextView release];
[Super dealloc];
}
-(IBAction) doWorking :( id) sender {
// Obtain the current time
NSDate * startTime = [NSDate date];
NSString * fetchedData = [self fechSomethingFromServer];
NSString * processedData = [self processData: fetchedData];
NSString * firstResult = [self caculateFirstResult: processedData];
NSString * secondResult = [self caculateSenondResult: processedData];
NSString * resultsSummary = [NSString stringWithFormat: @ "First: [% @] \ nSecond: [% @]", firstResult, secondResult];
// Assign a value to the text attribute of resultsTextView
ResultsTextView. text = resultsSummary;
NSDate * endTime = [NSDate date];
// Obtain the time difference in seconds.
NSLog (@ "Completed in % f seconds", [endTime timeIntervalSinceDate: startTime]);
}
@ End
Running result:
Initialization:
After you click Start Working, wait for about 10 seconds:
Console running result:
11:18:08. 360 SlowWorker [868: c07] Completed in 10.005586 seconds
2.2 Basic thread knowledge
Most modern operating systems support the concept of threads. Each process can contain multiple threads, all of which are performed simultaneously. All threads in a process share executable program code and the same global data. Each thread can also have some unique data. A thread can use a special structure called mutex or lock. This structure ensures that a specific code block cannot be run by multiple threads at a time. This helps ensure correct results.
When processing the thread again, the common problem is thread security. For example, in Cocoa Touch, the Foundation framework is generally considered thread-safe, while the UIKit framework is considered unsafe to a large extent. In the IOS application, all method calls for processing any UIKit object should be executed from the system thread, which is usually the main thread. By default, the main thread executes all operations of the IOS application (for example, Operations triggered by users ).
2.3 unit of work
The solution recommended by Apple for multi-threaded operations: Split long-running tasks into multiple work units and add these units to the execution queue. The system manages these queues for us and executes work units on multiple threads. We do not need to directly start and manage backend threads. We can get rid of too many "Registration" tasks involved in implementing concurrent applications. The system will do these tasks for us.