pthread_mutex_t VS @同步块? [英] pthread_mutex_t VS @synchronized block?

查看:88
本文介绍了pthread_mutex_t VS @同步块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆