线程锁

作者: xiari1991 | 来源:发表于2017-04-21 10:50 被阅读5次

    探讨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];
    

    取消阻塞线程.

    所以要求阻塞线程是在自线程中进行,解锁可以放在主线程或者是其他子线程中。

    相关文章

      网友评论

          本文标题:线程锁

          本文链接:https://www.haomeiwen.com/subject/qdqdzttx.html