iOS GCD 常用功能

获取主队列 异步执行 会开新线程


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            //执行耗时操作
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //回到主线程进行UI刷新操作
            };
        };

创建串行队列 开一个线程 顺序执行 1 和 2

dispatch_queue_t testQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);

dispatch_async(testQueue, ^{
            
            //执行代码 1
        });
dispatch_async(testQueue, ^{
            
            //执行代码 2
        });


创建并行队列 创建多个线程 1 和 2 无序执行

dispatch_queue_t testQueue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(testQueue, ^{
            
            //执行代码 1
        });
dispatch_async(testQueue, ^{
            
            //执行代码 2
        });


创建组队列

dispatch_queue_t globalQuene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_group_t group = dispatch_group_create();
             
            //任务1
            dispatch_group_enter(group);
            dispatch_async(globalQuene, ^{
                 NSLog(@"run task 1");
                sleep(1);
                dispatch_group_leave(group);
            });
             
            //任务2
            dispatch_group_enter(group);
            dispatch_async(globalQuene, ^{
                NSLog(@"run task 2");
                sleep(2);
                dispatch_group_leave(group);
            });
             
            //任务3
            dispatch_group_enter(group);
            dispatch_async(globalQuene, ^{
                NSLog(@"run task 3");
                sleep(3);
                dispatch_group_leave(group);
            });
             
       
           
            //任务3
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                NSLog(@"run task 4");
            });

你可能感兴趣的:(iOS GCD 常用功能)