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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。