iphone@synchronized(2011-10-1400:07:12)转载标签:杂谈分类:iOS@synchronized(self){}这种写法是什么作用?


如题:

@synchronized(self){
。。。。。。
}

保证此时没有其他线程对self对象进行修改

Usingthe@synchronizedDirective
The@synchronizeddirectiveisaconvenientwaytocreatemutexlocksontheflyinObjective-Ccode.The@synchronizeddirectivedoeswhatanyothermutexlockwoulddo—itpreventsdifferentthreadsfromacquiringthesamelockatthesametime.Inthiscase,however,youdonothavetocreatethemutexorlockobjectdirectly.Instead,yousimplyuseanyObjective-Cobjectasalocktoken,asshowninthefollowingexample:

-(void)myMethod:(id)anObj
{
@synchronized(anObj)
{
//Everythingbetweenthebracesisprotectedbythe@synchronizeddirective.
}
}
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{
@synchronized(self){
return[[myStringretain]autorelease];
}
}

istransformedinto:

-(NSString*)myString{
NSString*retval=nil;
pthread_mutex_t*self_mutex=LOOK_UP_MUTEX(self);
pthread_mutex_lock(self_mutex);
retval=[[myStringretain]autorelease];
pthread_mutex_unlock(self_mutex);
returnretval;
}

Thatisnotexactlycorrectbecausetheactualtransformismorecomplexandusesrecursivelocks,butitshouldgetthepointacross.