objective-c的锁

2019-10-31  本文已影响0人  Asteriskjs

objc里面的锁有很多种。

1.@property里面默认atomic:很少使用,因为效率问题
2.NSLock:很少使用,AFNetworking项目里面只能找到2个NSLock对象
3.GCD同步模拟锁:AFNetworking项目见到

//定义

dispatch_queue_t _conversationListQueue;//会话处理并发队列 安全机制参考自AFNetworking3.x

//初始化

_conversationListQueue = dispatch_queue_create("com.citylife.sdk.ios.conversationListQueue", DISPATCH_QUEUE_CONCURRENT);
//使用1

dispatch_barrier_sync(self->_conversationListQueue, ^{
        xxx

});
//使用2

dispatch_sync(self->_conversationListQueue, ^{
        xxx

});

4.信号量模拟锁:SDWebImage项目里见到

//定义信号量

@property (nonatomic, strong, nonnull) dispatch_semaphore_t weakCacheLock; // a lock to keep the access to `weakCache` thread-safe

//初始化信号量

self.weakCacheLock = dispatch_semaphore_create(1);
//使用宏定义模拟锁

SD_LOCK(self.weakCacheLock);
[self.weakCache setObject:obj forKey:key];

SD_UNLOCK(self.weakCacheLock);
//宏定义

#ifndef SD_LOCK

#define SD_LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
#endif

#ifndef SD_UNLOCK

#define SD_UNLOCK(lock) dispatch_semaphore_signal(lock);
#endif
上一篇 下一篇

猜你喜欢

热点阅读