dispatch_semaphore_t semaphoreLock;
@property(nonatomic, assign)NSInteger ticketSurplusCount;
/**
* 线程安全:使用 semaphore 加锁
* 初始化火车票数量、卖票窗口(线程安全)、并开始卖票
*/
- (void)initTicketStatusSave {
//打印当前线程
NSLog(@"currentThread---%@",[NSThread currentThread]);
NSLog(@"semaphore---begin");
semaphoreLock = dispatch_semaphore_create(1);
self.ticketSurplusCount = 50;
// queue1 代表北京火车票售卖窗口
dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
// queue2 代表上海火车票售卖窗口
dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
// queue3 代表深圳火车票售卖窗口
dispatch_queue_t queue3 = dispatch_queue_create("net.bujige.testQueue3", DISPATCH_QUEUE_SERIAL);
//queue4 代表广州火车票售卖窗口
dispatch_queue_t queue4 = dispatch_queue_create("net.bujige.testQueue4", DISPATCH_QUEUE_SERIAL);
// queue5 代表天津火车票售卖窗口
dispatch_queue_t queue5 = dispatch_queue_create("net.bujige.testQueue5", DISPATCH_QUEUE_SERIAL);
__weak typeof(self) weakSelf = self;
dispatch_async(queue1, ^{
NSLog(@"北京火车票售卖窗口");
[weakSelf saleTicketSafe];
});
dispatch_async(queue2, ^{
NSLog(@"上海火车票售卖窗口");
[weakSelf saleTicketSafe];
});
dispatch_async(queue3, ^{
NSLog(@"深圳火车票售卖窗口");
[weakSelf saleTicketSafe];
});
dispatch_async(queue4, ^{
NSLog(@"广州火车票售卖窗口");
[weakSelf saleTicketSafe];
});
dispatch_async(queue5, ^{
NSLog(@"天津火车票售卖窗口");
[weakSelf saleTicketSafe];
});
}
/**
* 售卖火车票(线程安全)
*/
- (void)saleTicketSafe {
while (1) {
//相当于加锁
dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
if (self.ticketSurplusCount > 0) { //如果还有票,继续售卖
self.ticketSurplusCount--;
NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%ld 窗口:%@", (long)self.ticketSurplusCount, [NSThread currentThread]]);
[NSThread sleepForTimeInterval:0.2];
} else {
//如果已卖完,关闭售票窗口
NSLog(@"所有火车票均已售完");
// 相当于解锁
dispatch_semaphore_signal(semaphoreLock);
break;
}
// 相当于解锁
dispatch_semaphore_signal(semaphoreLock);
}
}
输出结果:
2020-07-06 16:59:37.783410+0800 GCD[3557:1214746] 剩余票数:6 窗口:<NSThread: 0x283442ec0>{number = 9, name = (null)}
2020-07-06 16:59:37.990147+0800 GCD[3557:1214742] 剩余票数:5 窗口:<NSThread: 0x28345ec80>{number = 5, name = (null)}
2020-07-06 16:59:38.195653+0800 GCD[3557:1214741] 剩余票数:4 窗口:<NSThread: 0x283459c00>{number = 4, name = (null)}
2020-07-06 16:59:38.399338+0800 GCD[3557:1214745] 剩余票数:3 窗口:<NSThread: 0x28345eec0>{number = 3, name = (null)}
2020-07-06 16:59:38.605101+0800 GCD[3557:1214740] 剩余票数:2 窗口:<NSThread: 0x2834422c0>{number = 8, name = (null)}
2020-07-06 16:59:38.808133+0800 GCD[3557:1214746] 剩余票数:1 窗口:<NSThread: 0x283442ec0>{number = 9, name = (null)}
2020-07-06 16:59:39.009541+0800 GCD[3557:1214742] 剩余票数:0 窗口:<NSThread: 0x28345ec80>{number = 5, name = (null)}
2020-07-06 16:59:39.215021+0800 GCD[3557:1214741] 所有火车票均已售完
2020-07-06 16:59:39.215652+0800 GCD[3557:1214745] 所有火车票均已售完
2020-07-06 16:59:39.216028+0800 GCD[3557:1214740] 所有火车票均已售完
2020-07-06 16:59:39.216446+0800 GCD[3557:1214746] 所有火车票均已售完
2020-07-06 16:59:39.216697+0800 GCD[3557:1214742] 所有火车票均已售完
网友评论