关于锁的困惑

发布于 2024-12-15 11:39:49 字数 875 浏览 3 评论 0原文

关于锁,有一件事我不确定。我读过 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW16 但有一件事我不确定; @synchronize(或者一般来说只是互斥体)是否仅保护一部分代码(例如在方法内部)或锁定整个对象作为一个整体?

例如,两个线程处理这些方法,它们修改一个数组;

@synthesize m_myMutableArray;

-(void)threadA
{
    @synchronized(m_myMutableArray) {
         [m_myMutableArray removeAllObjects];
    }
}

-(void)threadB
{
    NSInteger asdf = 1;
    @synchronized(m_myMutableArray) {
         [m_myMutableArray addObject:asdf];

}

@synchronized 是否不执行任何操作,因为它们是两个独立的代码块,或者是在两种方法中锁定相同的互斥锁,这意味着 m_myMutableArray 是线程安全的?

谢谢

There is one thing I am not sure about when it comes to locks. I've read http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW16 but one thing I am not sure about; does @synchronize (or just mutex in general) protect only a section of code (say inside a method) or lock the entire object as a whole?

For example, two threads working on these methods, which modify an array;

@synthesize m_myMutableArray;

-(void)threadA
{
    @synchronized(m_myMutableArray) {
         [m_myMutableArray removeAllObjects];
    }
}

-(void)threadB
{
    NSInteger asdf = 1;
    @synchronized(m_myMutableArray) {
         [m_myMutableArray addObject:asdf];

}

Does @synchronized not do anything because they are two separate blocks of code, or is it the same mutex being locked in both methods, meaning m_myMutableArray is threadsafe?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若能看破又如何 2024-12-22 11:39:49

@synchronized 的“参数”是所谓的令牌或密钥,因此您可以拥有不同的锁定部分。只有当他们拥有相同的令牌时,他们才会互相阻止。对象本身没有被“锁定”。

因此,如果您有两个 @synchronized(foo) 和两个 @synchronized(bar),则 foo 部分会相互阻塞,但不会阻塞部分。

如果可能,您应该避免使用@synchronized,因为它非常慢,因为它的动态性质。

The "argument" to @synchronized is a so-called token or key so you can have different locked sections. They only block each other when they have the same token. The object themselves are not "locked".

So if you have two @synchronized(foo) and two @synchronized(bar), the foo sections block each other but will not block the bar sections.

If possible, you should avoid @synchronized as it's very slow, due to its dynamic nature.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文