美文网首页
iOS GCD(六)线程加锁

iOS GCD(六)线程加锁

作者: 你好哈喽哈喽 | 来源:发表于2020-06-11 16:36 被阅读0次

    线程枷锁分为九种方式 可以参考以上链接,我们只详细的讲解其中三种 semaphore, NSLock,@synchronized

    需要对线程加锁的原因很多 接下来我们只讲其中一种情况:
    当多条线程同时编辑一个任务时所造成的数据错乱
    举例说明:两个火车票销售窗口 共同销售车站总共的50张车票。看代码你最明白。

    错误案例:

    /**

    • 非线程安全:不使用 semaphore
    • 初始化火车票数量、卖票窗口(非线程安全)、并开始卖票
      */
    • (void)initTicketStatusNotSave {
      NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
      NSLog(@"semaphore---begin");

      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);

      __weak typeof(self) weakSelf = self;
      dispatch_async(queue1, ^{
      [weakSelf saleTicketNotSafe];
      });

      dispatch_async(queue2, ^{
      [weakSelf saleTicketNotSafe];
      });
      }

    /**

    • 售卖火车票(非线程安全)
      */
    • (void)saleTicketNotSafe {
      while (1) {

        if (self.ticketSurplusCount > 0) {  //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已卖完,关闭售票窗口
            NSLog(@"所有火车票均已售完");
            break;
        }
      

      }
      }

    输出结果(部分):
    2018-02-23 22:25:35.789072+0800 YSC-GCD-demo[20712:5258914] currentThread---<NSThread: 0x604000068880>{number = 1, name = main}
    2018-02-23 22:25:35.789260+0800 YSC-GCD-demo[20712:5258914] semaphore---begin
    2018-02-23 22:25:35.789641+0800 YSC-GCD-demo[20712:5259176] 剩余票数:48 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
    2018-02-23 22:25:35.789646+0800 YSC-GCD-demo[20712:5259175] 剩余票数:49 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
    2018-02-23 22:25:35.994113+0800 YSC-GCD-demo[20712:5259175] 剩余票数:47 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
    2018-02-23 22:25:35.994129+0800 YSC-GCD-demo[20712:5259176] 剩余票数:46 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
    2018-02-23 22:25:36.198993+0800 YSC-GCD-demo[20712:5259176] 剩余票数:45 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}

    可以看到在不考虑线程安全,不使用 semaphore 的情况下,得到票数是错乱的,这样显然不符合我们的需求,所以我们需要考虑线程安全问题。防止两条线程同时对此任务进行编辑,每次只能有一条线程执行此任务。所以就用到了线程加锁

    加锁方式一 dispatch_semaphore 自旋锁

    @interface ViewController (){
    NSInteger _ticketSurplusCount;
    dispatch_semaphore_t _semaphoreLock;
    NSLock _lock;
    }
    @end
    /
    *

    • 线程安全:使用 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);

      __weak typeof(self) weakSelf = self;
      dispatch_async(queue1, ^{
      [weakSelf saleTicketSafe];
      });

      dispatch_async(queue2, ^{
      [weakSelf saleTicketSafe];
      });
      }

    /**

    • 售卖火车票(线程安全)
      */
    • (void)saleTicketSafe {
      while (1) {
      // 相当于加锁
      dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);

        if (self.ticketSurplusCount > 0) {  //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已卖完,关闭售票窗口
            NSLog(@"所有火车票均已售完");
            
            // 相当于解锁
            dispatch_semaphore_signal(semaphoreLock);
            break;
        }
        
        // 相当于解锁
        dispatch_semaphore_signal(semaphoreLock);
      

      }
      }

    输出结果为:
    2018-02-23 22:32:19.814232+0800 YSC-GCD-demo[20862:5290531] currentThread---<NSThread: 0x6000000783c0>{number = 1, name = main}
    2018-02-23 22:32:19.814412+0800 YSC-GCD-demo[20862:5290531] semaphore---begin
    2018-02-23 22:32:19.814837+0800 YSC-GCD-demo[20862:5290687] 剩余票数:49 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
    2018-02-23 22:32:20.017745+0800 YSC-GCD-demo[20862:5290689] 剩余票数:48 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
    2018-02-23 22:32:20.222039+0800 YSC-GCD-demo[20862:5290687] 剩余票数:47 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
    ......
    2018-02-23 22:32:29.024817+0800 YSC-GCD-demo[20862:5290689] 剩余票数:4 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
    2018-02-23 22:32:29.230110+0800 YSC-GCD-demo[20862:5290687] 剩余票数:3 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
    2018-02-23 22:32:29.433615+0800 YSC-GCD-demo[20862:5290689] 剩余票数:2 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
    2018-02-23 22:32:29.637572+0800 YSC-GCD-demo[20862:5290687] 剩余票数:1 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
    2018-02-23 22:32:29.840234+0800 YSC-GCD-demo[20862:5290689] 剩余票数:0 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
    2018-02-23 22:32:30.044960+0800 YSC-GCD-demo[20862:5290687] 所有火车票均已售完
    2018-02-23 22:32:30.045260+0800 YSC-GCD-demo[20862:5290689] 所有火车票均已售完

    加锁方式二 @synchronized 互斥锁

    /**

    • 线程安全:使用 semaphore 加锁
    • 初始化火车票数量、卖票窗口(线程安全)、并开始卖票
      */
    • (void)initTicketStatusSave {
      NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
      NSLog(@"semaphore---begin");

      _semaphoreLock = dispatch_semaphore_create(1);

      _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);

      __weak typeof(self) weakSelf = self;
      dispatch_async(queue1, ^{
      [weakSelf saleTicketSafe];
      });

      dispatch_async(queue2, ^{
      [weakSelf saleTicketSafe];
      });
      }

    /**

    • 售卖火车票(线程安全)
      */
    • (void)saleTicketSafe {
      while (1) {
      // 相当于加锁
      @synchronized(self) {
      if (self.ticketSurplusCount > 0) { //如果还有票,继续售卖
      self.ticketSurplusCount--;
      NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", _ticketSurplusCount, [NSThread currentThread]]);
      [NSThread sleepForTimeInterval:0.2];
      } else { //如果已卖完,关闭售票窗口
      NSLog(@"所有火车票均已售完");
      break;
      }
      }
      }
      }

    输出结果为:
    2018-04-27 14:58:49.255255+0700 GCD[86633:4440145] 剩余票数:8 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.459695+0700 GCD[86633:4440148] 剩余票数:6 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:49.459695+0700 GCD[86633:4440145] 剩余票数:7 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.663997+0700 GCD[86633:4440145] 剩余票数:5 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.664065+0700 GCD[86633:4440148] 剩余票数:4 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:49.868848+0700 GCD[86633:4440145] 剩余票数:3 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.869419+0700 GCD[86633:4440148] 剩余票数:2 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:50.072308+0700 GCD[86633:4440145] 剩余票数:1 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:50.072308+0700 GCD[86633:4440148] 剩余票数:0 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:50.276839+0700 GCD[86633:4440148] 所有火车票均已售完
    2018-04-27 14:58:50.276839+0700 GCD[86633:4440145] 所有火车票均已售完

    加锁方式三 NSLock

    /**

    • 线程安全:使用 semaphore 加锁
    • 初始化火车票数量、卖票窗口(线程安全)、并开始卖票
      */
    • (void)initTicketStatusSave {
      NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
      NSLog(@"semaphore---begin");

      _semaphoreLock = dispatch_semaphore_create(1);

      _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);

      __weak typeof(self) weakSelf = self;
      dispatch_async(queue1, ^{
      [weakSelf saleTicketSafe];
      });

      dispatch_async(queue2, ^{
      [weakSelf saleTicketSafe];
      });
      }

    /**

    • 售卖火车票(线程安全)
      */
    • (void)saleTicketSafe {
      while (1) {
      // 相当于加锁
      [_lock lock];
      if (self.ticketSurplusCount > 0) { //如果还有票,继续售卖
      self.ticketSurplusCount--;
      NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", _ticketSurplusCount, [NSThread currentThread]]);
      [NSThread sleepForTimeInterval:0.2];
      } else { //如果已卖完,关闭售票窗口
      NSLog(@"所有火车票均已售完");
      break;
      }
      [_lock unlock];
      }
      }

    输出结果为:
    2018-04-27 14:58:49.255255+0700 GCD[86633:4440145] 剩余票数:8 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.459695+0700 GCD[86633:4440148] 剩余票数:6 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:49.459695+0700 GCD[86633:4440145] 剩余票数:7 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.663997+0700 GCD[86633:4440145] 剩余票数:5 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.664065+0700 GCD[86633:4440148] 剩余票数:4 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:49.868848+0700 GCD[86633:4440145] 剩余票数:3 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:49.869419+0700 GCD[86633:4440148] 剩余票数:2 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:50.072308+0700 GCD[86633:4440145] 剩余票数:1 窗口:<NSThread: 0x60000026fec0>{number = 3, name = (null)}
    2018-04-27 14:58:50.072308+0700 GCD[86633:4440148] 剩余票数:0 窗口:<NSThread: 0x600000270480>{number = 4, name = (null)}
    2018-04-27 14:58:50.276839+0700 GCD[86633:4440148] 所有火车票均已售完
    2018-04-27 14:58:50.276839+0700 GCD[86633:4440145] 所有火车票均已售完

    相关文章

      网友评论

          本文标题:iOS GCD(六)线程加锁

          本文链接:https://www.haomeiwen.com/subject/mfnbtktx.html