探讨iOS开发中各种锁
使用NSCondition实现多线程同步
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSLog(@"--");
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(2);
[_cityCondition lock];
[_cityCondition signal];
[_cityCondition unlock];
});
NSLog(@"%d", [self ff]);
NSLog(@"====");
return YES;
}
- (BOOL)ff {
if (!_cityCondition) {
_cityCondition = [[NSCondition alloc] init];
}
[_cityCondition lock];
[_cityCondition wait];
[_cityCondition unlock];
return 1;
}
NSCondition是线程同步,
[_cityCondition lock];
[_cityCondition wait];
[_cityCondition unlock];
阻塞线程。
[_cityCondition lock];
[_cityCondition signal];
[_cityCondition unlock];
取消阻塞线程.
所以要求阻塞线程是在自线程中进行,解锁可以放在主线程或者是其他子线程中。
网友评论