pthread_mutex_t VS @同步块? [英] pthread_mutex_t VS @synchronized block?
问题描述
static pthread_mutex_t gLock; //global
pthread_mutex_init(&gLock,NULL); //in init
pthread_mutex_lock(&gLock);
for(int i=0;i<[message count];i++)
CFSetAddValue(mSet, [message objectAtIndex:i]);
pthread_mutex_unlock(&gLock);
我的可可应用程序正在以pthread_mutex_t进入不响应模式.
My cocoa application is going in not responding mode with pthread_mutex_t.
@synchronized(mSet)
{
for(int i=0;i<[message count];i++)
CFSetAddValue(mSet, [message objectAtIndex:i]);
}
我的应用程序在同步块上运行良好.
My application is working fine with synchronized block.
为什么?
推荐答案
您正在将全局锁(针对所有实例的一个锁)与对象级递归锁(每个实例的一个锁,可以从以下位置多次获取)进行比较同一线程).它们通常是不可互换的-它们在操作和保护上彼此非常不同.
You're comparing a global lock (one lock for all instances) to an object level recursive lock (one lock per instance, which may be acquired multiple times from the same thread). These are not generally interchangeable -- they operate and protect very different from each other.
好消息是,您可以将pthread_mutex_t
用作每个实例唯一的递归锁,以实现与@synchronized
相同的保护程度.使用pthread_mutex_t
还可以使锁获取快得多.
The good news is, you can use pthread_mutex_t
as a recursive lock which is unique to each instance in order to achieve the same degree of protection as @synchronized
. Using pthread_mutex_t
also makes lock acquisitions much, much faster.
要使用pthread互斥锁实现与@synchronized
相同的效果,请将pthread_mutex_t gLock
声明为实例变量,然后在-init
中将其初始化为递归互斥体.最后,销毁-dealloc
中的互斥锁.
To achieve the same effect as @synchronized
using a pthread mutex, declare pthread_mutex_t gLock
as an instance variable, then initialize it as a recursive mutex in -init
. Finally, destroy the mutex in -dealloc
.
当然,如果子类和基类依赖于@synchronized
的语义来通过对象层次结构做正确的事情,则可能需要访问此锁.
Of course, sub- and base- classes may need access to this lock if they relied on the semantics of @synchronized
to do the right thing through the object hierarchy.
@synchronized
的veeeeeeery速度较慢(我最后检查过).
@synchronized
is veeeeeeery slow in comparison to a recursive pthread mutex (last I checked).
这篇关于pthread_mutex_t VS @同步块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!