Atom 多线程操作

99 阅读1分钟

2021-04-13 18:36:24.661610+0800 OCSummary[6980:399697] i a = 77, ioo = 40 2021-04-13 18:36:24.661619+0800 OCSummary[6980:399703] i b = 77, ipp = 37

2021-04-13 18:47:03.105592+0800 OCSummary[7032:406234] i b = 772, ipp = 401 2021-04-13 18:47:03.105592+0800 OCSummary[7032:406236] i a = 772, ioo = 396

同一时间2个线程都对 i + 1 操作, 导致都为 77

@property(atomic, assign) NSInteger i;
  self.i = 0;
dispatch_async(aQueue, ^{
    for (int i = 0; i < 50; i++) {
        self.i ++;
        NSLog(@"i a = %d, ioo = %d", self.i, i);
    }
});

dispatch_async(bQueue, ^{
    for (int i = 0; i < 50; i++) {
        self.i ++;
        NSLog(@"i b = %d, ipp = %d", self.i, i);
    }
});