iOS多线程为什么会出现不安全的情况

本文在于说明iOS应用的Objective-C代码的线程安全性。先是简单介绍一下线程安全的基本知识,然后通过一个小例子来观察非线程安全代码,最后会稍稍介绍一个可以用来分析线程安全隐患的工具。

1) 基础知识 (Threading Basics)


当启动一个应用时,iOS会对应创建一个进程(process)和一块为之分配的内存。简单地说,一个应用进程的内存包括三个部分:  (更详细的描述可以看 这里 ):

程序内存( program memory)存储应用的执行代码,它在执行时由一个指令指针(Instruction Pointer, IP)来跟踪程序执行位置。

堆( heap )存储由 [… alloc] init]来创建的对象。

堆栈( stack )则用于函数调用。存储参数和函数的局部变量。

一个应用进程默认有一个主线程。如果有多线程,所有线程共享 program memory  和  heap  , 每个线程又有各自的IP和堆栈。就是说每个线程都有自己的执行流程,当它呼叫一个方法时,其它线程是无法访问调用参数和该方法的局部变量的。而那些在堆(heap)上创建的对象却可以被其它线程访问和使用。

2) 实验 (Experiment)


建个使用如下代码的小程序:
  1. @interface FooClass {}    
  2. @property (nonatomic, assign) NSUInteger value;    
  3. - (void)doIt;    
  4. @end    
  5.     
  6. @implementation FooClass    
  7. @synthesize value;    
  8.     
  9. - (void)doIt {    
  10.      self.value = 0;    
  11.      for (int i = 0; i < 100000; ++i) {    
  12.           self.value = i;    
  13.      }    
  14.      NSLog(@"执行后: %d (%@)", self.value, [NSThread currentThread]);    
  15. }    
  16. @end  

这个类有一个整型属性value,并且会在doIt方法被连续增加100000次。执行完后,再将它的值和调用doIt方法的线程信息输出出来。 如下在AppDelegate中增加一个 _startExperiment方法,然后在 application:didFinishLaunchingWithOptions:方法中调用它 :
  1. - (void)_startExperiment {    
  2.      FooClass *foo = [[FooClass alloc] init];    
  3.      [foo doIt];    
  4.      [foo release];    
  5. }    
  6.     
  7. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
  8.      // …    
  9.      [self _startExperiment];    
  10.      return YES;         
  11. }  

因为这里还有多线程,所以结果很简单地显示value值为99999。

3) 线程安全 (Thread Safety)


如下以多线程并行执行doIt():
  1. - (void)_startExperiment {    
  2.       FooClass *foo = [[FooClass alloc] init];    
  3.       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    
  4.        
  5.    for (int i = 0; i < 4; ++i) {  //四个线程  
  6.      dispatch_async(queue, ^{    
  7.        [foo doIt];    
  8.      });    
  9.    }    
  10.    [foo release];    
  11.  }  

 
再执行,你的输出可能会类似如下的结果: (实际可能不一样):
 after execution: 19851 (NSThread: 0x6b29bd0>{name = (null), num = 3})  
 after execution: 91396 (NSThread: 0x6b298f0>{name = (null), num = 4})  
 after execution: 99999 (NSThread: 0x6a288a0>{name = (null), num = 5})  
 after execution: 99999 (NSThread: 0x6b2a6f0>{name = (null), num = 6})  

并不是每个线程的value都是99999。这是因为现在的代码并不是线程安全的。

所谓线程安全就是代码运行在多线程环境下和运行在单线程环境下是一样的。

是什么导致了这个行为呢? 正如前面所说的每个线程都有其自己的IP和堆栈,但却共享堆(heap)。例子中的FooClass是创建在堆上的,所有线程都可以使用。下图展示了两个线程在执行doIt方法时的冲突: :

Thread 1和Thread 2正在不同的位置执行。doIt()并没有对多线程的执行进行保护,它的实现是非线程安全的。

一个将doIt()变为线程安全的方式是在其函数体外使用如下编译指示符(directive):

新的代码如下所示:
  1. - (void)doIt {    
  2.    @synchronized(self) {    
  3.      self.value = 0;     
  4.      for (int i = 0; i < 100000; ++i) {    
  5.        self.value = i;    
  6.      }    
  7.      NSLog(@"after execution: %d (%@)", self.value, [NSThread currentThread]);         
  8.    }    
  9.  }   

使用 @synchronized指示符 , 每个线程会在doIt()互斥地使用self。不过因为目前的代码中@synchronized包住了整个函数体,并不能达到并行执行的效果。

另一种同步访问机制是使用GCD: Grand Central Dispatch (GCD) .

 4) 如何识别非线程安全的代码 (How to identify not thread safe code)


上面例子太过于简单了。现实中,花了时间写好的代码,常常遇到死锁、崩溃,或者一些无法复现的问题。总之和期望的行为不一样。

线程问题的主因是共享或全局状态(state)数据。多个对象访问一个全局变量,或者在堆中分享了共同对象,再或者向共同的存储空间写入数据。在前面例子中所共享的状态是self, 对应的访问也就是 self.value。例子中所展示要比实际上的情况简单太多了,事实上确定使用的共享或全局状态(share or global state)并不容易。

解决方案就是写了一个工具,由多线程调用的函数来识别。下面是这个工具的核心概念。

工具主要包含了四个类: 
MultiThreadingAnalysis的实例用于记录一个线程对方法的调用,   ThreadingTrace类和 MethodExecution类用来输出 MultiThreadingAnalysis整理的分析结果 MultiThreadingAnalysisHook类则用于hook到对象并追踪它被调用的所有方法。




MultiThreadingAnalysis类提供两个方法 :
  • recordCallToMethod:ofClass:onThread: 记录某个方法在某个线程上被调用了。
  • threadingTraceOfLastApplicationRun 需要在分析完成后调用。
  1. @interface MultiThreadingAnalysis : NSObject    
  2.     
  3.      - (void)recordCallToMethod:(NSString*)methodName    
  4.                ofClass:(NSString*)className    
  5.               onThread:(NSString*)threadID;    
  6.              
  7.      - (ThreadingTrace*) threadingTraceOfLastApplicationRun;    
  8.              
  9. @end    


分析结果由 ThreadingTrace来处理 . 它包含了一组 MethodExecution实例,每一个都表示了一个线程对一个方法的调用 :
  1. /*   
  2.  * An instance of this class captures   
  3.  * which methods of which classes have been   
  4.  * called on which threads.   
  5.  */    
  6. @interface ThreadingTrace : NSObject    
  7.      /*   
  8.       * Set of MethodExecution   
  9.       */    
  10.      @property (nonatomic, readonly) NSSet *methodExecutions;    
  11.      - (void)addMethodExecution:(MethodExecution*)methodExec;    
  12. @end    
  13.     
  14. /*   
  15.  * An instance of this class represents a call   
  16.  * to a method of a specific class on a thread   
  17.  * with a specific threadID.   
  18.  */    
  19. @interface MethodExecution : NSObject    
  20.      @property (nonatomic, retain) NSString *methodName;    
  21.      @property (nonatomic, retain) NSString *className;    
  22.      @property (nonatomic, retain) NSString *threadID;    
  23. @end    

为了尽可能方法地记录方法的调用,我使用了NSProxy来hook对一个对象所有方法的调用。 MultiThreadingAnalysisHook类继承自 NSProxy,并在 forwardInvocation:  方法解析对target对象的调用. 在重定位到target对象前,会先使用一个 MultiThreadingAnalysis实例来记录下这次调用。
 
  1. @interface MultiThreadingAnalysisHook : NSProxy    
  2.       @property (nonatomic, retain) id target;    
  3.       @property (nonatomic, retain) MultiThreadingAnalysis *analysis;    
  4.  @end    
  5.      
  6.  @implementation MultiThreadingAnalysisHook    
  7.      
  8.  -(void)forwardInvocation:(NSInvocation*)anInvocation {    
  9.        
  10.    [self.analysis recordCallToMethod:NSStringFromSelector([anInvocation selector])    
  11.                     ofClass:NSStringFromClass([self.target class])    
  12.                 onThread:[NSString stringWithFormat:@"%d", [NSThread currentThread]]];    
  13.        
  14.    [anInvocation invokeWithTarget:self.target];    
  15.  }    
  16.  @end  

现在就可以使用了。在你要分析的类中创建一个私有方法 _withThreadingAnalysis  。 这个方法要创建一个 MultiThreadingAnalysisHook实例并且将target指到self。在自行指定的初始化函数中调用 _withThreadingAnalysis并返回其结果(HOOK的动作)。这样就达到使用 MultiThreadingAnalysisHook实例将原本对象的self封装起来,并可以记录所有外部对象的调用
 
  1. @implementation YourClass    
  2.      
  3.  - (id)init {    
  4.       //... do init stuff here    
  5.       return [self _withThreadingAnalysis];    
  6.  }    
  7.      
  8.  - (id)_withThreadingAnalysis {    
  9.    MultiThreadingAnalysisHook *hook =     
  10.      [[MultiThreadingAnalysisHook alloc] init];    
  11.    hook.target = self;    
  12.    return hook;    
  13.  }    
  14.  @end  


此后就可以调用 MultiThreadingAnalysis   的 threadingTraceOfLastApplicationRun方法获取分析结果。最简单地输出到文本文件,结果如下:

begin threading analysis for class FooClass
   method doIt (_MultiThreadAccess_)
   method init (_SingleThreadAccess_)  

如果某个方法被多线程调用(标注为 _MultiThreadAccess_), 你可以看到更多详细信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值