-(void)viewDidLoad {
dispatch_sync(dispatch_get_main_queue(), ^{
[self doSomething];
});
}
複製代碼
-(void)viewDidLoad {
dispatch_sync(serialQueue, ^{
[self doSomething];
});
}
複製代碼
-(void)viewDidLoad {
dispatch_async(global_queue, ^{
NSLoag(@"1");
[self performSelector:@selector(printLog)
withObjec:nil
afterDelay:0];
NSLog(@"3")
});
}
-(void)printLog {
NSLog(@"2")
}
複製代碼
@interface UserCenter()
{
dispatch_queue_t concurrent_queue;
NSMutableDictionary *userCenterDic;
}
@end
@implementation UserCenter
- (id)init
{
self = [super init];
if (self) {
concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
userCenterDic = [NSMutableDictionary dictionary];
}
return self;
}
- (id)objectForKey:(NSString *)key
{
__block id obj;
dispatch_sync(concurrent_queue, ^{
obj = [userCeneterDic objectForKey:key];
});
return obj;
}
- (void)setObject:(id)obj forKey:(NSString *)key
{
dispatch_barrier_async(concurrent_queue, ^{
[userCenterDic setObject:obj, forKey:key];
});
}
@end
複製代碼
@interface GroupObject()
{
dispatch_queue_t concurrent_queue;
NSMutableArray <NSURL *> *urlArr;
}
@end
@implementation GroupObject
- (id)init
{
self = [super init];
if (self) {
concurrent_queue = dispatch_queue_create("concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
urlArr = [NSMutableArray array];
}
return self;
}
- (void)handle
{
dispatch_group_t group = dispatch_group_create();
for (NSURL *url in urlArr) {
dispatch_group_async(group, concurrent_queue, ^{
NSLog(@"url is %@", url);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"完成");
})
}
@end
複製代碼
重寫main方法,地城控制變動任務及執行完成狀態,以及任務退出 重寫start方法,自行控制任務狀態多線程
系統經過KVO移除isFinished = YES的NSOperation併發
dispatch_semaphore_create()
struct semaphore {
int value;
List<thread>;
}
dispatch_semaphore_wait()
{
S.value = S.value - 1;
if S.value < 0 then Block(S.List); => 阻塞線程
}
dispatch_semaphore_signal()
{
S.value = S.value + 1;
if S.value <= 0 then wakeup(S.List);
}
複製代碼