//
// GlobalQueueSerial.h
// TestProj
//
// Created by Wesley on 2016/11/17.
// Copyright © 2016年 Wesley. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface GlobalQueueSerial : NSObject
//+(instancetype)sharedInstance;
//+(dispatch_queue_t)queue;
+(void)addBlock:(void (^)(void))block;
@end
//
// GlobalQueueSerial.m
// TestProj
//
// Created by Wesley on 2016/11/17.
// Copyright © 2016年 Wesley. All rights reserved.
//
#import "GlobalQueueSerial.h"
@interface GlobalQueueSerial()
{
dispatch_queue_t _aQueue;
dispatch_group_t _queueGroup;
}
@end
@implementation GlobalQueueSerial
+(instancetype)sharedInstance
{
static GlobalQueueSerial*sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[GlobalQueueSerial alloc] init];
});
return sharedInstance;
}
+(dispatch_queue_t)queue
{
return [[GlobalQueueSerial sharedInstance] queue];
}
+(dispatch_group_t)group
{
return [[GlobalQueueSerial sharedInstance] group];
}
+(void)addBlock:(void (^)(void))block
{
dispatch_queue_t aQueue = [GlobalQueueSerial queue];
// create queue group
dispatch_group_t queueGroup = [GlobalQueueSerial group];
// task 1
dispatch_group_wait(queueGroup, DISPATCH_TIME_FOREVER);
dispatch_group_async(queueGroup, aQueue, block);
}
-(instancetype)init
{
if (self = [super init]) {
_aQueue = dispatch_queue_create("sticker", DISPATCH_QUEUE_SERIAL);
_queueGroup = dispatch_group_create();
}
return self;
}
-(dispatch_queue_t)queue
{
if (!_aQueue) {
_aQueue = dispatch_queue_create("sticker", DISPATCH_QUEUE_SERIAL);
}
return _aQueue;
}
-(dispatch_group_t)group
{
if (!_queueGroup) {
_queueGroup = dispatch_group_create();
}
return _queueGroup;
}
-(void)dealloc
{
#if(!__has_feature(objc_arc))
dispatch_release(queueGroup);
#endif
}
@end
Usage:
for (int i = 0; i < 10; ++i) {
[GlobalQueueSerial addBlock:^{
NSLog(@"task %d begin.", i);
NSLog(@"task %d end.", i);
}];
}
网友评论