标签:mic init info img elf png stat oid Once
#import "ViewController.h" #import <libkern/OSAtomic.h> @interface ViewController () @property (nonatomic,assign) int ticket; //@property (nonatomic,assign) OSSpinLock lock; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // self.lock = OS_SPINLOCK_INIT; self.ticket=50; [self ticketsTest]; // Do any additional setup after loading the view. } -(void)saleTicket{ //静态创建、则不需要新建属性 static OSSpinLock lock = OS_SPINLOCK_INIT; //若后面是个函数、则需 /* static OSSpinLock lock = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ lock = OS_SPINLOCK_INIT; }); */ //其他线程执行到这里时,发现锁被加锁了 就会再这排队等待、直到这个锁被打开 //加锁 OSSpinLockLock(&lock); int ticket = self.ticket; sleep(.2); ticket--; self.ticket=ticket; NSLog(@"%d",self.ticket); //解锁 OSSpinLockUnlock(&lock); } -(void)ticketsTest{ dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_async(queue, ^{ for (int i =0; i<5; i++) { [self saleTicket]; } }); dispatch_async(queue, ^{ for (int i =0; i<5; i++) { [self saleTicket]; } }); }
标签:mic init info img elf png stat oid Once
原文地址:https://www.cnblogs.com/ZhangShengjie/p/12275038.html