GCD 实现生产-消费 模式
2014-10-16 18:01
393 查看
#import "ViewController.h" @interface ViewController (){ } @property (nonatomic,strong) dispatch_semaphore_t sema; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. _sema = dispatch_semaphore_create(1); dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_queue_create("custom_dis", 0); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ if (![[NSThread currentThread] isMainThread]) { NSLog(@"===异步线程==============="); } for (int i = 0; i<10; i++) { dispatch_semaphore_wait(_sema, DISPATCH_TIME_FOREVER); dispatch_group_async(group, queue, ^{ if (![[NSThread currentThread] isMainThread]) { NSLog(@"===异步线程==============="); } [self doCustomSomting]; }); } }); dispatch_group_wait(group, DISPATCH_TIME_FOREVER); } -(void)doCustomSomting{ sleep(2); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ if (![[NSThread currentThread] isMainThread]) { NSLog(@"===异步线程==============="); } sleep(1); dispatch_async(dispatch_get_main_queue(), ^{ if ([[NSThread currentThread] isMainThread]) { NSLog(@"===主线程==============="); } NSLog(@"=====compeletSomting========="); dispatch_semaphore_signal(_sema); }); }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
相关文章推荐
- blockingQueue实现消费-生产模式
- 多线程初探之使用Lock实现生产-消费模式
- 关于java多线程浅析一:简单实现生产消费模式
- 使用Lock锁机制实现 多线程的 多生产 多消费 模式。
- 使用Condition实现多线程之间调用(生产消费模式)
- 通过pthread_mutex_lock和pthread_cond_wait实现生产消费模式,并且生产一次消费一次
- 整理修改的一个日志类,用生产与消费模式实现,消费模式用了异步执行
- redis队列-生产消费模式-简单实现
- 生产/消费模式实现
- 生产消费模式的几种实现
- 使用C#的泛型队列Queue实现生产消费模式
- 用java实现生产和消费
- 机房重构利用策略模式+简单工厂实现消费金额的计算
- 初次尝试ActiveMQ,实现简单的消息生产和消息消费
- 条件变量实现生产消费问题
- java中多线程模拟(多生产,多消费,Lock实现同步锁,替代synchronized同步代码块)
- ActiveMQ使用线程池实现消息的生产与消费
- ios开发单例模式——使用GCD实现单例模式 & 非ARC单例模式 &使用GCD和线程锁实现单例模式
- iOS下单例模式实现(一)(objective-c arc gcd)
- 生产消费模式