OSSpinLock与os_unfair_lock
OSSpinLock
已经被Apple废弃,因为线程安全问题,就不说了。想了解的可以百度搜OSSpinLock安全问题。
os_unfair_lock
API说明
1、OS_UNFAIR_LOCK_INIT ,初始化锁
2、os_unfair_lock_lock ,获得锁
3、os_unfair_lock_unlock ,解锁
下面是自己的理解和例子代码
#import <Foundation/Foundation.h>
@interface NSLockTest : NSObject
- (void)forTest;
@end
#import "NSLockTest.h"
#import <os/lock.h>
@interface NSLockTest()
@end
@implementation NSLockTest
os_unfair_lock theLock ;
- (void)forTest
{
// 创建信号量
theLock = OS_UNFAIR_LOCK_INIT;
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(download1) object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(download2) object:nil];
[thread2 start];
}
-(void)download1
{
os_unfair_lock_lock(&theLock);
NSLog(@"第一个线程同步操作开始");
sleep(8);
NSLog(@"第一个线程同步操作结束");
os_unfair_lock_unlock(&theLock);
}
-(void)download2
{
os_unfair_lock_lock(&theLock);
NSLog(@"第二个线程同步操作开始");
sleep(1);
NSLog(@"第二个线程同步操作结束");
os_unfair_lock_unlock(&theLock);
}
@end
注意
os_unfair_lock,apple文档中空空如也。
1、申明,os_unfair_lock theLock ;
2、初始化,theLock = OS_UNFAIR_LOCK_INIT;
3、加锁,os_unfair_lock_lock(&theLock);
4、解锁,os_unfair_lock_unlock(&theLock);
5、思路和其他互斥锁类似。