3

在方法体上使用 @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");
    }
}

问:案例 2 是否围绕 '-(void) calledMethod' 创建了两个互斥锁?

编辑当我使用这种互斥锁时,我在主线程上收到一个信号 SIGINT。如果有人可以建议我出了什么问题,我将附上屏幕截图?在此处输入图像描述

4

1 回答 1

4

是的,同时没有。@synchronized根据docs是递归锁,这意味着创建了两个互斥锁,但它们不会导致死锁并且都被正确销毁。

然而,需要注意的一点是,这种令人敬畏的“递归”锁定非常昂贵,如果情况支持,可能应该使用另一种形式的互斥锁(NSLock、NSConditionLock 等)。

@synchronized是一个了不起的关键字,不要误会我的意思,但不要随便把它扔到不需要它的地方。

于 2013-03-01T13:04:12.880 回答