@interface ViewController ()
{
int _totalCount; // 火车票总票数
int _surplusCoynt; // 剩余票数
NSLock *_lock; // 互斥锁
}
@end
// 设置剩余票数
_surplusCoynt = 100;
_lock = [[NSLock alloc] init]; // 创建互斥锁,多个线程共享使用
// 自己创建并行队列
dispatch_queue_t queue1 = dispatch_queue_create("火车站", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue1, ^{
[self saleTickets:queue1];
});
dispatch_queue_t queue2 = dispatch_queue_create("代售点", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue2, ^{
[self saleTickets:queue2];
});
#pragma mark - 售票方法
- (void)saleTickets:(dispatch_queue_t)queue
{
while (_surplusCoynt > 0) {
[_lock lock]; // 获取互斥锁并且添加
const char *queueLabel = dispatch_queue_get_label(queue);
NSString *label = [NSString stringWithUTF8String:queueLabel];
NSLog(@"当前火车票由%@售出,余票:%d张", label, _surplusCoynt);
_surplusCoynt--;
[_lock unlock];
}
}