Common multithreading mistakes beginners make on iPhone

后端 未结 2 825
栀梦
栀梦 2020-12-13 01:10

I just introduced multithreading into my app JUST to get a silly UIActivityIndicatorView to work. Well, the activity indicator works, alright -- but now my app crashes somet

相关标签:
2条回答
  • 2020-12-13 01:48

    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.

    0 讨论(0)
  • 2020-12-13 01:52

    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.

    0 讨论(0)
提交回复
热议问题