IOS GCD

转载: IOS GCD

GCD 是在iOS开发多线程技术里面,使用最简单,执行效率最高的,是相对底层的API,都是c函数。核心是d往ispatch queue里面添加执行的任务,由queue管理任务的执行。
在之前的面试中,经常会被大神问道:用过多线程吗?知道多线程的?知道各种实现多线的方法有什么区别吗?等等。之前只是会用多线程,但是对于面试这一关,只是会用还不够,还需要能把基本知识记住。在这推荐一个帖子,看了就懂个大概了 http://my.oschina.Net/u/2429584/blog/491771
dispatch queue有两种:串行serial queue和并行concurrent queue。无论是哪种queue都是FIFO(先进先出)

一、串行 serial queue

特点:执行queue中的第一个任务,结束后在执行第二个任务,第二个任务结束在执行第三个任务,,,,任何一个任务的执行必须在上一个任务的执行结束后。

1、获取mainQueue。mainQueue会在主线程中执行,即:主线程中执行队列中的各个任务
dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
     NSLog(@"第1个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
 });//在block里写要执行的任务(代码)
    dispatch_async(mainQueue, ^{
        NSLog(@"第2个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(mainQueue, ^{
        NSLog(@"第3个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(mainQueue, ^{
        NSLog(@"第4个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(mainQueue, ^{
        NSLog(@"第5个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码) 
2 、 自己创建serial queue。//自己创建的serial queue不会在主线程中执行,queue会开辟一个子线程,在子线程中执行队列中的各个任务
dispatch_queue_t mySerialQueue = dispatch_queue_create("MySerialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(mySerialQueue, ^{
    NSLog(@"第1个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(mySerialQueue, ^{
    NSLog(@"第2个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(mySerialQueue, ^{
    NSLog(@"第3个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(mySerialQueue, ^{
    NSLog(@"第4个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(mySerialQueue, ^{
    NSLog(@"第5个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)

二、并行 concurrent

queue是另外一种队列。其特点:队列中的任 务,第一个先执行,不等第一个执行完毕,第二个就开始执行了,不等第二个任务执行完毕,第三个就开始执行了,以此类推。后面的任务执行的晚,但是不会等前面的执行完才执行。

获得concurrent queue的方法有2种:

1、获得global queue。
//第一个参数控制globalQueue的优先级,一共有4个优先级DISPATCH_QUEUE_PRIORITY_HIGH、DISPATCH_QUEUE_PRIORITY_DEFAULT、DISPATCH_QUEUE_PRIORITY_LOW、DISPATCH_QUEUE_PRIORITY_BACKGROUND。第二个参数是苹果预留参数,未来会用,目前填写为0
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
        NSLog(@"第1个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第2个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第3个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第4个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第5个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第6个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第7个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第8个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第9个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
    dispatch_async(globalQueue, ^{
        NSLog(@"第10个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
    });//在block里写要执行的任务(代码)
2、自己创建concurrent queue
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("MyConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第1个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第2个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第3个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第4个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第5个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第6个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第7个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第8个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第9个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"第10个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//在block里写要执行的任务(代码)

concurrent queue会根据需要开辟若干个线程,并行执行队列中的任务(开始较晚的任务未必最后结束,开始较早的任务未必最先完成),开辟的线程数量 取决于多方面因素,比如:任务的数量,系统的内存资源等等,会以最优的方式开辟线程---根据需要开辟适当的线程。

延时调用

  - (void)after{
double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        NSLog(@"Hello");
//    });//dispatch_after函数是延迟执行某个任务,任务既可以在mainQueue中进行也可以在其他queue中进行.既可以在serial队列里执行也可以在concurrent队列里执行。

dispatch_queue_t myConcurrentQueue = dispatch_queue_create("MyConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_after(popTime, myConcurrentQueue, ^(void){
    NSLog(@"world");
});
}

若干任务执行完之后,想执行某任务

  - (void)group
{
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("MyConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);

//dispatch_group_async用于把不同的任务归为一组
//dispatch_group_notify当指定组的任务执行完毕之后,执行给定的任务
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第1个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第2个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第3个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第4个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第5个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第6个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_notify(group, myConcurrentQueue, ^{
    NSLog(@"group中的任务都执行完毕之后,执行此任务。所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//dispatch_group_notify group中的任务都执行完毕之后,执行的任务
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第7个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_group_async(group, myConcurrentQueue, ^{
    NSLog(@"第8个任务,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});

}

数据安全

为了保证访问同一个数据时,数据的安全,我们可以使用serial queue解决数据安全访问的问题。
//serial queue的缺陷是:后面的任务 必须等待 前面的任务 执行完毕 才能执行
//对于往数据库写入数据 使用serial queue无疑能保证数据的安全。
//对于从数据库中读取数据,使用serial queue就不太合适了,效率比较低。使用concurrent queue无疑是最合适的。
//真实的项目中,通常既有对数据库的写入,又有数据库的读取。

//下面给出了 既有数据库数据读取,又有数据库数据写入的处理方法dispatch_barrier_async

  - (void)barrier{
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("MyConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取一些数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取另外一些数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取这些数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取那些数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});



dispatch_barrier_async(myConcurrentQueue, ^{
    NSLog(@"写入某些数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});//dispatch_barrier_async就像一道墙,之前的任务都并行执行,执行完毕之后,执行barrier中的任务,之后的任务也是并行执行。



dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取XXX数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取OOXX数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取aaa数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
dispatch_async(myConcurrentQueue, ^{
    NSLog(@"读取bbb数据,所在线程%@,是否是主线程:%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
 }
来一段swift代码
let myConcurrentQueue : dispatch_queue_t = dispatch_queue_create("MyConcurrentQueue", DISPATCH_QUEUE_CONCURRENT)
dispatch_async(myConcurrentQueue, {
    print("读取一些数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})
dispatch_async(myConcurrentQueue, {
print("读取另外一些数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})
dispatch_async(myConcurrentQueue, {
    print("读取这些数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})
dispatch_async(myConcurrentQueue, {
    print("读取那些数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})



dispatch_barrier_async(myConcurrentQueue, {
    print("写入某些数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})//dispatch_barrier_async就像一道墙,之前的任务都并行执行,执行完毕之后,执行barrier中的任务,之后的任务也是并行执行。



dispatch_async(myConcurrentQueue, {
    print("读取XXX数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})
dispatch_async(myConcurrentQueue, {
    print("读取OOXX数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread
)
})
///当然也可以这样
dispatch_async(myConcurrentQueue, {
    print("读取aaa数据,所在线程\(NSThread.currentThread()),是否是主线程:\(NSThread.currentThread().isMainThread))")
})
dispatch_async(myConcurrentQueue, {    print("读取bbb数据,所在线程%@,是否是主线程:%d",NSThread.currentThread(),NSThread.currentThread().isMainThread)
})

GCD中提供了API让某个任务执行若干次。

  - (void)apply {
NSArray *array = [NSArray arrayWithObjects:@"红楼梦",@"水浒传",@"三国演义",@"西游记", nil];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t index) {
    NSLog(@"%@所在线程%@,是否是主线程:%d",[array objectAtIndex:index],[NSThread currentThread],[[NSThread currentThread] isMainThread]);
});
}

dispatch_once 用于定义那些只需要执行一次的代码,比如单例的创建

 - (void)once
  {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    NSLog(@"只执行一次");
    //这个block里的代码,在程序执行过程中只会执行一次。
    //比如在这里些单例的初始化
    //        static YourClass *instance = nil;
    //        instance = [[YourClass alloc] init];
});
  }

GCD里有一些API是dispatch_sync

//dispatch_async无需等block执行完,继续执行dispatch_async后面的代码
//dispatch_sync必须等block执行完,才继续执行dispatch_sync后面的代码

- (void)syn
 {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

//    dispatch_sync(queue, ^{
//        for (int i = 0; i < 10; i++) {
//            NSLog(@"%d",i);
//        }
//    });
//    NSLog(@"haha");


dispatch_async(queue, ^{
    for (int i = 0; i < 10; i++) {
        NSLog(@"%d",i);
    }
});
NSLog(@"haha");
}

dispatch_async_f往队列里放函数指针,队列控制相应函数的执行,不在是控制block的执行

void function (NSString * str){
    NSLog(@"调用一个函数指针   参数是%@",str);
}

- (void)functionPoint
 {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async_f(queue, @"你好", function);//函数指针对应的函数类型:必须没有返回值,参数必须是void *。函数指针对应的参数,由dispatch_async_f第二个参数提供,可以是任意对象类型。   
 } 

fun dispatch_asysn_f(_ queue: dispatch_queue_t!,_ content: UnsafeMutablePointer<void>,_ work : dispatch_function_t)

queue 提交到的队列,队列的类型决定了是串行还是并行执行队列中的任务
context 传递给work的参数
work 执行的函数(C语言函数)


   
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 简介 GCD(Grand Central Dispatch)是在macOS10.6提出来的,后来在iOS4.0被引...
    sunmumu1222阅读 894评论 0 2
  • 一、GCD的API 1. Dispatch queue 在执行处理时存在两种Dispatch queue: 等待现...
    doudo阅读 508评论 0 0
  • GCD笔记 总结一下多线程部分,最强大的无疑是GCD,那么先从这一块部分讲起. Dispatch Queue的种类...
    jins_1990阅读 784评论 0 1
  • 简介 GCD(Grand Central Dispatch)是在macOS10.6提出来的,后来在iOS4.0被引...
    JerryLMJ阅读 2,342评论 1 11
  • 一. 重点: 1.dispatch_queue_create(生成Dispatch Queue) 2.Main D...
    BestJoker阅读 1,598评论 2 2