Multi-Thread-GCD
-GCD all APIs are in Libdispatch.dylib, Xcode will automatically import this library
-Main header file: #import
1.to create a global concurrent queue(most commonly used),Allows the task to execute concurrentlydispatch_queue_tQueue=Dispatch_get_global_queue(Dispatch_queue_priority_default,0);To add a task to a global queue asynchronous executionDispatch_async(Queue,^{NSLog(@ "-----(0_0)------%@",[NsthreadCurrentThread]);});2.Create a serial queue,let the task execute one after anotherconst char *label: queue name, C-language string//dispatch_queue_attr_t attr: Queue properties dispatch_queue_t queue = dispatch_queue_create ( "Down.queue" null3. Create a home column ( tasks added to the main queue will automatically be placed in the main thread Line dispatch_queue_t queue = dispatch_get_main_queue ();
GCD inter-thread communication
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 执行耗时的异步操作... dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程,执行UI刷新操作 });});
GCD Other uses
- Delay execution
- Deferred execution is not used
sleepForTimeInterval
because the current thread is stuck
Non-GCD
// 一旦定制好延时任务后,不会卡主当前线程 [self performSelector:@selector(download) withObject:@"http://abc.jpg" afterDelay:3];
GCD
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 2秒后执行这里的代码...});
- Disposable code
- Use the Dispatch_once function to ensure that a piece of code
程序运行过程中
is executed only 1 times
static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{ // 只执行1次的代码(这里面默认是线程安全的)});
dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index){ // 执行10次代码,index顺序不确定});
- Barrier
- It does not execute until after the execution of the previous task, and the task after it is completed before it executes
不能是全局的并发队列
所有的任务都必须在一个队列中
dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);
dispatch_group_tGroup=Dispatch_group_create();Dispatch_group_async(Group,Dispatch_get_global_queue(dispatch_queue_priority_default0^{//perform 1 time-consuming asynchronous operations (groupdispatch_get_global _queue (dispatch_queue_priority_default0^{//perform 1 time-consuming asynchronous operations (groupdispatch_get_main_ Queue (), ^{//etc. before the asynchronous operation is complete, return to the main thread ...
Multithreaded Development----GCD