2021-09-29  本文已影响0人  howhyone

一、synchronized

@interface ViewController ()

@property (nonatomic, assign) NSUInteger ticketCount;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.ticketCount = 20;
    [self testSaleTicket];
}

- (void)testSaleTicket{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 5; i++) {
            [self saleTicket];
        }
    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 5; i++) {
            [self saleTicket];
        }
    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 3; i++) {
            [self saleTicket];
        }
    });

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < 10; i++) {
            [self saleTicket];
        }
    });
}

- (void)saleTicket{
    @synchronized (self) {
        if (self.ticketCount > 0) {
            self.ticketCount--;
            NSLog(@"当前余票还剩:%ld张",self.ticketCount);

        }else{
            NSLog(@"当前车票已售罄");
        }
    }
}

@end

对应的关键代码objc_sync_enter和objc_sync_exit
objc_sync_enter关键流程分析:

获取当前线程的缓存链表结构,查看缓存链表是否存在对象object
如果存在,则执行lockCount++,更新缓存并结束流程
如果当前线程的缓存链表中未找到对象object缓存,则查看listp总链表结构
若总链表结构存在对象object,则threadCount++
若总链表结构不存在对象object,则新建一个SyncData,且将lockCount、threadCount置为1,最后更新缓存
objc_sync_exit关键流程分析:

获取当前线程的缓存链表结构,查看缓存链表是否存在对象object
如果存在,则执行lockCount--
如果当前的lockCount==0,则threadCount--,更新缓存并结束流程

参考链接:https://zhuanlan.zhihu.com/p/297912855

上一篇下一篇

猜你喜欢

热点阅读