Objective-C 编程语言官网文档(十二)-线程
2012-06-06 15:22
405 查看
声明:本文档仅为个人学习过程中顺手翻译之作,方便开发的同胞借鉴参考。如有觉得译的不好不到位的地方,欢迎指正,将及时做出更正
尽量尊重原文档,因为首次Objective-C,有些地方可能直译了没有注意该语言的专有词,希望指正。如需转载,请注明出处
我的编程环境:
IDE:XCODE4.3.1
OS:MACOSX10.7.4
文章来译自:http://developer.apple.com/
线程Objective-C提供了对线程同步以及异常绑定(“Exception
Handling.”)的支持。要打开对这些特性的支持。可以使用GCC3.3以及更新版本
-fobjc-exceptions开关。
[b]注意:这个开关只有在MacOSXv10.3以及更新的版本中才能使用,因为对异常处理以及同步的运行时支持在早前的版本中还没有出现
Objective-C支持多线程。因此,两个线程可以在同时去改变同一个对象,这时就可能在程序中产生问题。为了避免一段代码在运行时被多个线程操作,Objective-C提供了
@synchronized()指令.
@synchronized()指令会为一段代码加锁以在同一时间确保只有一个线程可以使用。其它的线程被锁定直到当前获得锁的线程退出受保护的代码。
@synchronized()指令只有一个参数,可以是任何Objective-C对象,包括
self.这个对象被称为互斥信号量.它允许一个线程锁定一个代码块以防止同一时间被其它线程访问。你应该使用不同的信号来保护程序的不同的临界区。最安全的方法就是在产生多线程的状况之前创建好所有需要的互斥信号对象,以防止出现紊乱状况。
11-1展示了使用
self来作为当前对象的实例方法同步访问的信号量。与此类似,你可以使用类对象为相关类的类方法进行同步保护。在后面一种情况中,同一时间只会有一个线程可以执行这个类方法,因为对于所有的调用者来说,都只有一个类对象可被使用。
11-1
-(void)criticalMethod |
{ |
@synchronized(self){ |
//Criticalcode. |
... |
} |
} |
Account类中获得了一个信号量并用它来锁定该关键流程快。
Account类可以在它的
initialize方法中创建该信号量.
11-2
Account*account=[AccountaccountFromString:[accountFieldstringValue]]; |
//Getthesemaphore. |
idaccountSemaphore=[Accountsemaphore]; |
@synchronized(accountSemaphore){ |
//Criticalcode. |
... |
} |
@synchronized()块正常退出或者通过异常退出后。
当在
@synchronized()块中的代码抛出一个异常时,Objective-C运行时会捕获这个异常,释放该信号量(这样被保护的代码即可以被其它线程执行),并再次抛出该异常给下一个异常处理器。
英文原文:
Threading
Objective-Cprovidessupportforthreadsynchronizationandexceptionhandling,whichareexplainedinthischapterandin“ExceptionHandling.”Toturnonsupportforthesefeatures,
usethe
-fobjc-exceptionsswitchoftheGNUCompilerCollection(GCC)version3.3andlater.
Note:UsingeitherofthesefeaturesinaprogramrenderstheapplicationrunnableonlyinMacOSXv10.3andlaterbecause
runtimesupportforexceptionhandlingandsynchronizationisnotpresentinearlierversionsofthesoftware.
Objective-Csupportsmultithreadinginapplications.Therefore,twothreadscantrytomodifythesameobjectatthesametime,asituationthat
cancauseseriousproblemsinaprogram.Toprotectsectionsofcodefrombeingexecutedbymorethanonethreadatatime,Objective-Cprovidesthe
@synchronized()directive.
The
@synchronized()directivelocksasectionofcodeforuse
byasinglethread.Otherthreadsareblockeduntilthethreadexitstheprotectedcode—thatis,whenexecutioncontinuespastthelaststatementinthe
@synchronized()block.
The
@synchronized()directivetakesasitsonlyargumentanyObjective-Cobject,including
self.
Thisobjectisknownasamutualexclusionsemaphoreormutex.Itallowsathreadtolockasectionofcodetoprevent
itsusebyotherthreads.Youshoulduseseparatesemaphorestoprotectdifferentcriticalsectionsofaprogram.It’ssafesttocreateallthemutualexclusionobjectsbeforetheapplicationbecomesmultithreaded,toavoidraceconditions.
Listing11-1showscodethatuses
selfasthemutex
tosynchronizeaccesstotheinstancemethodsofthecurrentobject.Youcantakeasimilarapproachtosynchronizetheclassmethodsoftheassociatedclass,usingtheclassobjectinsteadof
self.
Inthelattercase,ofcourse,onlyonethreadatatimeisallowedtoexecuteaclassmethodbecausethereisonlyoneclassobjectthatissharedbyallcallers.
Listing11-1Lockingamethodusingself
-(void)criticalMethod |
{ |
@synchronized(self){ |
//Criticalcode. |
... |
} |
} |
Accountclass
andusesittolockthecriticalsection.The
Accountclasscouldcreatethesemaphoreinits
initializemethod.
Listing11-2Lockingamethodusingacustomsemaphore
Account*account=[AccountaccountFromString:[accountFieldstringValue]]; |
//Getthesemaphore. |
idaccountSemaphore=[Accountsemaphore]; |
@synchronized(accountSemaphore){ |
//Criticalcode. |
... |
} |
every
@synchronized()blockisexitednormallyorthroughanexception.
Whencodeinan
@synchronized()block
throwsanexception,theObjective-Cruntimecatchestheexception,releasesthesemaphore(sothattheprotectedcodecanbeexecutedbyotherthreads),andrethrowstheexceptiontothenextexceptionhandler.
[/b]
相关文章推荐
- Objective-C 编程语言官网文档(十二)-线程
- Objective-C 编程语言官网文档(七)-关联引用
- Objective-C 编程语言官网文档(十三 终结篇)-词汇表
- Objective-C 编程语言官网文档(八)-快速枚举
- Objective-C 编程语言官网文档(十三 终结篇)-词汇表
- Objective-C 编程语言官网文档(五)-属性的声明
- Objective-C 编程语言官网文档(二)-对象,类以及消息
- Objective-C 编程语言官网文档(十)-选择器
- Objective-C 编程语言官网文档(十)-选择器
- Objective-C 编程语言官网文档(五)-属性的声明
- Objective-C 编程语言官网文档(四)-协议
- Objective-C 编程语言官网文档(五)-属性的声明
- Objective-C 编程语言官网文档(一)-简介
- Objective-C 编程语言官网文档(一)-简介
- Objective-C 编程语言官网文档(六)-类别以及扩展
- Objective-C 编程语言官网文档(三)-如何定义类
- Objective-C 编程语言官网文档(九)-静态行为
- Objective-C 编程语言官网文档(十一)-异常的处理
- Objective-C 编程语言官网文档(三)-如何定义类
- Objective-C 编程语言官网文档(九)-静态行为