Common multithreading mistakes beginners make on iPhone

六眼飞鱼酱① 提交于 2019-11-28 16:55:20
Brad Larson

This question has some good resources on Cocoa multithreading: "Where can I find a good tutorial on iPhone/Objective c multithreading?"

I also highly recommend reading the new Concurrency Programming Guide (however, ignore the blocks and dispatch queues, as Grand Central Dispatch is not yet available on iPhone OS iOS 4.0 just added blocks and GCD), because it makes a strong case for using structures like NSOperation and NSOperationQueue as an alternative to manually created threads. For information on manually created threads, refer to the Threading Programming Guide.

As RC mentions, the single biggest source of crashes with multithreaded Cocoa applications is simultaneous access to a shared resource. The @synchronized directive is not the fastest, as pointed out by Colin Wheeler, so you might want to use NSLock to protect access to your shared resources. However, locking of any sort can be expensive, which is why I've been migrating my applications over to using single-wide NSOperationQueues for access to these resources. The performance improvements have been significant.

Another problem area with Cocoa and multithreading comes from user interface updates. All UI updates in Cocoa must be done on the main thread, or instability can result. If you have a background thread performing a calculation, make sure to wrap whatever method updates the UI in a -performSelectorOnMainThread:withObject:waitUntilDone: method call.

Probably the most common mistake beginners make (in any language) when working with threads is allowing access to mutable shared resources without guards/mutexes. You guard resources like:

@synchronized(sharedData)
{
   // modify sharedData safely
}

You'll want to limit the amount of data shared between threads and if it must be shared, prefer immutable objects in order to reduce contention caused by synchronization.

Managing threads is another place where trouble can arise. Here is a document reference specific to the use of threads in the iPhone.

http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html.

Without providing code, it's anyone's guess as to what is wrong with your app, but I would start with making sure you are correctly managing the creation and termination of the thread as well as putting particular attention to any shared resources that thread attempts to access.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!