关于锁的困惑
例如,两个线程处理这些方法,它们修改一个数组;
@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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@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.