Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

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?

like image 253
Parag Bafna Avatar asked Feb 27 '12 10:02

Parag Bafna


1 Answers

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).

like image 87
justin Avatar answered Sep 29 '22 02:09

justin