我正在编写一个我想要线程安全的 Objective-C 类。为此,我使用 pthreads 和 a pthread_rwlock
(使用@synchronized
是矫枉过正,我想了解更多关于 pthreads 的知识)。锁在对象指定的init
方法中初始化并在 中销毁dealloc
。我有三种操作锁的方法;readLock
, writeLock
, unlock
. 这三个方法只是调用相关的 pthread 函数,目前没有别的。
下面是两个对象方法,它们都需要 writeLock:
-(void)addValue:(const void *)buffer
{
[self writeLock];
NSUInteger lastIndex = self.lastIndex;
[self setValue:buffer atIndex:(lastIndex == NSNotFound) ? 0 : lastIndex+1];
[self unlock];
}
-(void)setValue:(const void *)buffer atIndex:(NSUInteger)index
{
[self writeLock];
//do work here
[self unlock];
}
调用setAddValue:
将首先获得一个写锁,然后调用setValue:atIndex:
它也将尝试获得一个写锁。文档指出,发生这种情况时行为未定义。因此,如何在尝试获取锁之前检查线程是否有锁?
(我可以确保关键部分不进行触发另一个锁定请求的调用,但这意味着代码重复,我想保持我的代码 DRY)。