Multithreading GCD for iOS development and multithreading gcd for ios
1. GCD (Grand Centrol Dispath)
Parallel: both macro and micro-systems are digging holes with two more shovel and two more traps in an hour.
Concurrency: at the macro level, I think they are all digging holes. At the micro level, they are using a shovel to dig holes. In an hour, they dug two traps.
Summary: for a single cpu, most of the processes are executed concurrently, that is, a shovel. If you look at me, it's just that the interval is short and the user doesn't feel it.
Application:
GCD includes:
(1) In actual use (by default, the system has a serial queue main_queue and a parallel queue global_queue:
[Cpp]View plaincopy
- Dispatch_queue_t globalQ = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
- Dispatch_queue_t mainQ = dispatch_get_main_queue ();
)
// Dispatch_get_global_queue (0, 0) The first 0 is the priority and the second reserved field
Dispatch_async (dispatch_get_global_queue (0, 0), ^ {
// Here It Can Be A Data Request
NSString * result = [self requestData: parameter];
// Here, the main thread is returned to refresh the data.
Dispatch_async (dispatch_get_main_queue (), ^ {
[MainTableView reloadData];
});
});
Example:
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
NSURL * url = [NSURL URLWithString: @ "http://www.baidu.com"];
NSError * error;
NSString * data = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: & error];
If (data! = Nil ){
Dispatch_async (dispatch_get_main_queue (), ^ {
NSLog (@ "call back, the data is: % @", data );
});
} Else {
NSLog (@ "error when download: % @", error );
}
});
(2) You can also create one by yourself (I am not very useful)
A serial queue, as its name implies, must be executed concurrently.
// Create your own serial queue
Dispatch_queue_t queue = dispatch_queue_create ("com. class15.queue", DISPATCH_QUEUE_SERIAL );
// Asynchronous execution thread
Dispatch_async (queue, ^ {
NSLog (@ "Task 1: % @ % d", [NSThread currentThread], [NSThread currentThread]. isMainThread );
});
The parallel queue is obtained through dispatch_get_global_queue. The system creates three dispatch queue with different priorities.
// Create your own queue
Dispatch_queue_t queue = dispatch_queue_create ("com. class15.comcr1_queue", DISPATCH_QUEUE_CONCURRENT );
Dispatch_async (queue, ^ {
NSLog (@ "Task 1: % @ % d", [NSThread currentThread], [NSThread currentThread]. isMainThread );
});