无标题文章

GCD

队列:
1、系统提供了5种队列:
主队列:
一个主队列:dispatch_get_main_queue();
四个全局队列:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
2、自定义队列:
//串行队列
dispatch_queue_create("seriaQueuel", DISPATCH_QUEUE_SERIAL)
//并行队列
dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT)

概念,GCD会负责线程的创建和调度需要执行的任务,由系统直接提供线程管理.
我们来理解一下简单的概念:
1、串行:串行队列中只能有一个线程,一旦task添加到该队列后,其余的任务等待,知道task运行结束,其他的任务才能依次进入。

dispatch_queue_t queue = dispatch_queue_create("串行队列", DISPATCH_QUEUE_SERIAL);
无标题文章_第1张图片
Paste_Image.png

2、并行:并行队列中有多个线程,多个任务被任意分配到线程中。

dispatch_queue_t queue = dispatch_queue_create("并行队列", DISPATCH_QUEUE_CONCURRENT);
无标题文章_第2张图片
Paste_Image.png

3、同步:不具备开发新的线程

dispatch_sync(queue, ^{
    
});

4、异步:具备开发新的线程

dispatch_async(queue, ^{
    
});

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
// Perform long running process

dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI
    
});
}); 

http://www.cnblogs.com/kenshincui/p/3983982.html
https://developer.apple.com/videos/play/wwdc2015/718/

  //dispatch semaphore
- (void)dispatchSemaphoreDemo {
//创建semaphore
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"start");
    [NSThread sleepForTimeInterval:1.f];
    NSLog(@"semaphore +1");
    dispatch_semaphore_signal(semaphore); //+1 semaphore
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"continue");
}

你可能感兴趣的:(无标题文章)