ios之线程安全
如题:
@synchronized(self){
}
保证此时没有其他线程对self对象进行修改
Usingthe@synchronizedDirective
The@synchronizeddirectiveisaconvenientwaytocreatemutexlocksontheflyinObjective-Ccode.The@synchronizeddirectivedoeswhatanyothermutexlockwoulddo—itpreventsdifferentthreadsfromacquiringthesamelockatthesametime.Inthiscase,however,youdonothavetocreatethemutexorlockobjectdirectly.Instead,yousimplyuseanyObjective-Cobjectasalocktoken,asshowninthefollowingexample:
-(void)myMethod:(id)anObj
{
}
Theobjectpassedtothe@synchronizeddirectiveisauniqueidentifierusedtodistinguishtheprotectedblock.Ifyouexecutetheprecedingmethodintwodifferentthreads,passingadifferentobjectfortheanObjparameteroneachthread,eachwouldtakeitslockandcontinueprocessingwithoutbeingblockedbytheother.Ifyoupassthesameobjectinbothcases,however,oneofthethreadswouldacquirethelockfirstandtheotherwouldblockuntilthefirstthreadcompletedthecriticalsection.
Asaprecautionarymeasure,the@synchronizedblockimplicitlyaddsanexceptionhandlertotheprotectedcode.Thishandlerautomaticallyreleasesthemutexintheeventthatanexceptionisthrown.Thismeansthatinordertousethe@synchronizeddirective,youmustalsoenableObjective-Cexceptionhandlinginyourcode.Ifyoudonotwanttheadditionaloverheadcausedbytheimplicitexceptionhandler,youshouldconsiderusingthelockclasses.
Formoreinformationaboutthe@synchronizeddirective,seeTheObjective-CProgrammingLanguage.
TheobjectiveClanguagelevelsynchronizationusesthemutex,justlikeNSLockdoes.Semanticallytherearesomesmalltechnicaldifferences,butitisbasicallycorrecttothinkofthemastwoseperateinterfaceimplementedontopofacommon(moreprimitive)entity.
InparticularwithanNSLockyouhaveanexplicitlockwhereaswith@synchronizeyouhaveanimplicitlockassociatedwiththeobjectyouareusingtosynchronize.Thebenefitofthelanguagelevellockingisthecompilerunderstandsitsoitcandealwithscopingissues,butmechanicallytheyarethebehavebasicallythesame.
Youcanthinkof@synchronizeasbasicallyacompilerrewrite:
-(NSString*)myString{
}
istransformedinto:
-(NSString*)myString{
}
Thatisnotexactlycorrectbecausetheactualtransformismorecomplexandusesrecursivelocks,butitshouldgetthepointacross.
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。