简体   繁体   English

使用@synchronized指令 - Objective-C Mutex Lock iOS

[英]Use of @synchronized directive - Objective-C Mutex Lock iOS

Using @synchronized directive on method body 在方法体上使用@synchronized指令

-(void)testSynchronizeMethod:(int)value
{
    @synchronized(value)
    {
        int value1 = 100; //sample line 1
        int value2 = 120; //sample line 2
        [self calledMethod];
    }
}

//case 1
-(void)calledMethod
{
    NSLog(@"is @synchronized directive applied to this method");
    NSLog(@"what happens if I enclose this method with @synchronized directive");
}

**or**
//case 2
-(void)calledMethod
{
    @synchronized(value){
        NSLog(@"is @synchronized directive applied to this method");
        NSLog(@"what happens if I enclose this method with @synchronized directive");
    }
}

Q: In case 2 Are Two mutex locks created around '-(void)calledMethod'? 问:在案例2中是否在' - (void)calledMethod'周围创建了两个互斥锁?

EDIT I'm getting a signal SIGINT on main thread while I'm using such mutex locks. 编辑我正在使用这样的互斥锁时在主线程上获得SIGINT信号。 I'm attaching a screen grab if someone could suggest me what is going wrong? 如果有人能告诉我出了什么问题,我会附上一个屏幕抓取? 在此输入图像描述

Yes, and no at the same time. 是的,但不是在同一时间。 @synchronized is a recursive lock according to the docs , meaning that two mutex locks are created, but they don't cause a deadlock and are both destroyed properly. @synchronized是根据一个递归锁的文档 ,这意味着创建两个互斥锁,但他们不会导致僵局,都破坏了正常。

One thing to note, however, is that this awesome 'recursive' locking is quite expensive, and another form of mutex (NSLock, NSConditionLock, etc.) should probably be used if the situation supports it. 然而,有一点需要注意的是,这种令人敬畏的“递归”锁定非常昂贵,如果情况支持,可能应该使用另一种形式的互斥(NSLock,NSConditionLock等)。

@synchronized is an amazing keyword, don't get me wrong, but don't just go willy-nilly throwing it in places that don't need it. @synchronized是一个了不起的关键词,不要误会我的意思,但不要随便把它扔到不需要它的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM