此递归同步调用如何不死锁? [英] How does this recursive synchronized call not deadlock?

查看:76
本文介绍了此递归同步调用如何不死锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组全部同步到类对象的方法(不能使用self,因为该对象的多个实例可以在多个线程中使用).其中一些方法调用了类中的其他方法,这些方法也可以在类对象上同步.某种程度上,这可以正常工作,并且不会导致僵局.

I have a set of methods that all synchronize to the class object (can't use self, because multiple instances of this object could be used in multiple threads). Some of those methods call other methods in the class that also synchronize on the class object. Somehow this works and does not cause the deadlock I would expect it to.

我认为testA将被阻止运行,因为testB已经对类对象进行了锁定,但这显然不是这种情况.

I would assume that testA would be blocked from running because testB already has a lock on the class object, but this apparently isn't the case.

@synchronized正在执行某些特殊操作,或者这是基础互斥锁的功能吗?

Is it something special that @synchronized is doing or is this a feature of the underlying mutex locks?

有效的示例代码:

- (NSUInteger)testA
{
    @synchronized(self.class)
    {
        NSLog(@"Doing something in A");
    }
    return 1;
}

- (void)testB
{
    @synchronized(self.class)
    {
        NSLog(@"Doing something in B");
        NSLog(@"A returned: %i", [self testA]);
    }
}

调用testB时,输出为:

When calling testB the output is:

Doing something in B
Doing something in A
A returned: 1

推荐答案

Mauricio的评论正确.来自 TOCPL :

Mauricio's comment is correct. From TOCPL:

Objective-C同步功能支持递归和可重入代码.一个线程可以递归方式多次使用一个信号量.其他线程被阻止使用它,直到该线程释放由此获得的所有锁为止;也就是说,每个@synchronized()块都会正常退出或通过异常退出.

The Objective-C synchronization feature supports recursive and reentrant code. A thread can use a single semaphore several times in a recursive manner; other threads are blocked from using it until the thread releases all the locks obtained with it; that is, every @synchronized() block is exited normally or through an exception.

这篇关于此递归同步调用如何不死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆