美文网首页
iOS性能优化实战篇-多线程异步加锁问题

iOS性能优化实战篇-多线程异步加锁问题

作者: DeveloperBlock | 来源:发表于2019-10-13 10:33 被阅读0次
这个问题是我在做人脸识别、活体认证的功能时遇到的一个bug。
  • 问题现象
    测试同学在测试人脸识别时偶尔出现程序Crash,经过初步诊断发现问题时出在第三方SDK,当时因为项目进度比较急,就直接把奔溃日记、代码截图抛给了第三方对接的同学。
    结果经第三方同学说他们测试没发现奔溃问题,说后面处理了就告诉我,然后就没有然后了...

  • 重现问题
    一段时间过后,测试小同学又来向我反馈这个问题时,我发誓我一定要解决这个bug。(补充:测试是个男同学!)
    于是我又打开项目调试了好多次,终于复现了bug,找到了那段坑爹的代码,仔细的研究了一番,终于找到了问题!

  • 坑爹代码如下

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
//音频播放器
@property(nonatomic,strong)AVAudioPlayer * audioPlayer;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //业务场景:
    //摄像头不断获取图像,然后每张图像进行异步比对,同时不断将结果返回代理,然后进行语音操作提示。
    dispatch_queue_t currentQueue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 1; i<4; i++) {
        dispatch_async(currentQueue, ^{
            NSLog(@"播放次数--- %d ---",i);
            [self playBackgroundSound:i];
        });
    }
}

//播放音频
- (void) playBackgroundSound:(NSInteger )num {
    
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"test" ofType: @"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    
    @synchronized (_audioPlayer) {
        NSLog(@"%@",[NSThread currentThread]);
        if ([_audioPlayer isPlaying]) {
            [_audioPlayer stop];
        }
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error:nil];
        NSLog(@"次数- %ld ---播放器:%@ ",num,_audioPlayer);
        [_audioPlayer play];
        NSLog(@"次数- %ld ---播放器:%@ ",num,_audioPlayer);
    }
}

  • 分析问题
    第三方SDK开发小同学,为了避免并发队列异步执行时出现资源竞争问题,特地好心地给这个任务加了个锁。
@synchronized (_audioPlayer) {

 //这是一个坑爹的初始化,切换音频内容必须进行一个初始化!!!
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error:nil]; 
}

然而问题恰恰就出现在这里,小同学千不该万不该把 _audioPlayer对象作为了锁对象。

  1. 锁对象_audioPlayer 初始化是在锁的内部,会导致多个任务进入锁内执行;
  2. 初始化是什么:给一个对象分配存储空间,并返回这个对象(新指针地址)!!!也就是锁对象_audioPlayer会一直变!
  3. 当任务1初始化返回一个 A指针赋值给_audioPlayer,正准备发送"play"消息时,任务2也初始化一个B指针赋值给_audioPlayer,原来的A指针没有变量持有,内存即被收回。此时"A指针"变成了一个野指针,此时继续向它发生"play"消息,程序自然会崩溃!
  • 处理方案
  1. 将锁对象"_audioPlayer"换成"self"。(最简单、效果最好
  2. 去掉锁,将异步换成同步执行。

相关文章

网友评论

      本文标题:iOS性能优化实战篇-多线程异步加锁问题

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