iphone:Grand Central Dispatch

简介:

queue有三种 

  • Main: tasks execute serially on your application’s main thread

  • Concurrent: tasks start executing in FIFO order, but can run concurrently.

  • Serial: tasks execute one at a time in FIFO order

  • (1)serial queues(串行队列)又称私有调度队列(private),一般用再对特定资源的同步访问上。我们可以根据需要创建任意数量的串行队列,每一个串行队列之间是并发的。
  • (2)并行队列,又称global dispatch queue。并行队列虽然可以并发的执行多个任务,但是任务开始执行的顺序和其加入队列的顺序相同。我们自己不能去创建并行调度队列。只有三个可用的global concurrent queues。
  • (3)main dispatch queue 是一个全局可用的串行队列,其在行用程序的主线程上执行任务。此队列的任务和应用程序的主循环(run loop)要执行的事件源交替执行。因为其运行在应用程序的主线程,main queue经常用来作为应用程序的一个同步点

 

 

Important functions in this C API
Creating and releasing queues
dispatch_queue_t dispatch_queue_create(const char *label, NULL); // serial queue void dispatch_release(dispatch_queue_t);

Putting blocks in the queue

typedef void (^dispatch_block_t)(void);

void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

Getting the current or main queue

dispatch_queue_t dispatch_get_current_queue();
void dispatch_queue_retain(dispatch_queue_t); 
// keep it in the heap until dispatch_release

 

Main Queue:         dispatch_queue_t  dispatch_get_main_queue();

Global Queue:      dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

Serial:                 dispatch_queue_create("identifier",NULL);

 

 

Example ... assume we fetched an image from the network (this would be slow).

- (void)viewWillAppear:(BOOL)animated
{
    dispatch_queue_t   downloadQueue = dispatch_queue_create(“image downloader”, NULL);
    dispatch_async(downloadQueue, ^{
         NSData  *imageData = [NSData dataWithContentsOfURL:networkURL];
//UIKit只能在main_queue中 dispatch_async(dispatch_get_main_queue(), ^{
             UIImage *image = [UIImage imageWithData:imageData];
             self.imageView.image = image;
             self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
             self.scrollView.contentSize = image.size;
         });
    });
    dispatch_release(downloadQueue);

 本文转自老Zhan博客园博客,原文链接:http://www.cnblogs.com/mybkn/archive/2012/05/06/2486152.html,如需转载请自行联系原作者

相关文章
|
3月前
|
API 调度 iOS开发
多线程和异步编程:什么是 GCD(Grand Central Dispatch)?如何在 iOS 中使用 GCD?
多线程和异步编程:什么是 GCD(Grand Central Dispatch)?如何在 iOS 中使用 GCD?
28 1
|
前端开发 API
patch使用
+ put:对所有资源进行更新 + patch:对部分资源进行更新 put使用方法和post相同,但是put是幂等的。
|
开发工具 git
生成patch
生成patch
|
监控
Dispatch Source 应用
Dispatch Source 源是一个偏底层的函数集合,使用时CPU负荷非常小,尽量不占资源,开发过程中大多是配合定时器使用。
161 0
|
Android开发
一分钟学会使用9-patch
背景 之前项目开发一般都是写逻辑,UI方面的操作用的比较少。 图片也是直接使用设计师提供的。 因此一般情况下不需要用到9-patch图。 然而,最近项目中分配给我的功能用到了。
1448 0