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_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.
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
.
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
is veeeeeeery slow in comparison to a recursive pthread mutex (last I checked).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With