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);
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.
Why?
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.
The good news is, you can use
pthread_mutex_tas a recursive lock which is unique to each instance in order to achieve the same degree of protection as@synchronized. Usingpthread_mutex_talso makes lock acquisitions much, much faster.To achieve the same effect as
@synchronizedusing a pthread mutex, declarepthread_mutex_t gLockas an instance variable, then initialize it as a recursive mutex in-init. Finally, destroy the mutex in-dealloc.Of course, sub- and base- classes may need access to this lock if they relied on the semantics of
@synchronizedto do the right thing through the object hierarchy.@synchronizedis veeeeeeery slow in comparison to a recursive pthread mutex (last I checked).