IPhone IOS multi-thread programming Summary

Source: Internet
Author: User

The following are some of your friendly support:

Made a product, need popularity support a bit, Android and iPhone 91 market search # super junior mission #, or directly to the page to download the http://m.ixingji.com/m.html? P = x16

Old rules: first post two official e articles

1) threading programming guide

Http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW7

2) concurrency (concurrency) programming guide

Http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html#//apple_ref/doc/uid/TP40008091-CH100-SW6


There are two differences between them. If you are good at text and patient, you can filter the following.

Recommendation

1) [cocoa] multi-thread nsthread of cocoa

Http://blog.csdn.net/kesalin/article/details/6698146

2) use multiple threads of the iPhone to implement the "ticket sales system" (hands-on Guide to iPhone development-basics)

Http://blog.csdn.net/dongfengsun/article/details/4794010

3) concurrency (Mac & iPhone) (1)

Http://hi.baidu.com/songxiaoweiss/blog/item/699971d7c6c579de50da4b51.html

4) concurrency Learning (Mac & iPhone) (2)

Http://hi.baidu.com/songxiaoweiss/blog/item/82b08d13912cb4dca6ef3f29.html


I found many articles on iOS multi-threaded coding on the Internet, basically speaking of three methods.

1) detachnewthreadselector or performselectorinbackground

// Nsthread method, start the thread detaches a new thread and uses the specified selector as the thread entry point. + (void) detachnewthreadselector :( SEL) aselector totarget :( ID) atarget withobject :( ID) anargument // method in nsobject, start the thread invokes a method of the worker er on a new background thread. -(void) implements mselectorinbackground :( SEL) aselector withobject :( ID) methods in Arg // nsobject, because the updated UI can only be executed in the main thread. Therefore, this function is mainly used for the subthread to call the aselector in the main thread to update the ui or parameters of the main thread. -(Void) specified mselecw.mainthread :( SEL) aselector withobject :( ID) Arg waituntildone :( bool) Wait


In a classic example, the main thread needs to connect to the network to update the List image:

[1] main thread call

[NSThread detachNewThreadSelector:@selector(downloadimg:) toTarget:self withObject:url];

[2] After the download is completed, the main thread is notified and the list image is updated.

        [self performSelectorOnMainThread:@selector(stateIsLoading) withObject:nil waitUntilDone:NO];


2) regular army, nsthread

- (id)init;// designated initializer- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;


In this example, I copy it from the Internet and want to describe the synchronization and lock of the thread. The best example may be the ticket sales system that sells tickets at the same time in multiple windows. We know that synchronized is used for synchronization in Java. Although the iPhone does not provide a keyword similar to synchronized in Java, it provides an nscondition object interface. View the nscondition interface description. We can see that nscondition is the lock object under the iPhone, so we can use nscondition to implement thread security in the iPhone.

//  SellTicketsAppDelegate.himport <UIKit/UIKit.h> @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {     int tickets;     int count;     NSThread* ticketsThreadone;     NSThread* ticketsThreadtwo;     NSCondition* ticketsCondition;     UIWindow *window; }@property (nonatomic, retain) IBOutlet UIWindow *window;@end


Implementation File

// Sellticketsappdelegate. mimport "sellticketsappdelegate. H "@ implementation sellticketsappdelegate @ synthesize window;-(void) applicationdidfinishlaunching :( uiapplication *) Application {tickets = 100; Count = 0; // Lock Object ticketcondition = [[nscondition alloc] init]; ticketsthreadone = [[nsthread alloc] initwithtarget: Self selector: @ selector (run) object: Nil]; [reset setname: @ "thread-1"]; [ticketsthreadone start]; ticketsthreadtwo = [[nsthread alloc] initwithtarget: Self selector: @ selector (run) object: Nil]; [reset setname: @ "thread-2"]; [ticketsthreadtwo start]; // [nsthread detachnewthreadselector: @ selector (run) totarget: Self withobject: Nil]; // override point for customization after application launch [Window makekeyandvisible];}-(void) run {While (true) {// lock [ticketscondition lock]; If (tickets> 0) {[nsthread sleepfortimeinterval: 0.5]; Count = 100-tickets; nslog (@ "Current ticket count: % d, sold: % d, thread name: % @", tickets, count, [[nsthread currentthread] Name]); tickets --;} else {break;} [ticketscondition unlock];}-(void) dealloc {[ticketsthreadone release]; [ticketsthreadtwo release]; [ticketscondition release]; [Window release]; [Super dealloc];} @ end


Note: After the initwithtarget Initialization is complete, you must call start to start the thread.


"The difference between the two methods is that the previous one will immediately create a thread to do things, and the other one will init even if you alloc, however, the thread will not be created until we manually call start to start the thread. This delay implementation idea is useful in many resource-related aspects. In the latter way, We can configure the thread before starting the thread, for example, setting the stack
Size, thread priority ."


3) thread queue nsoperationqueue

Refer to the article to use nsoperationqueue to simplify multi-thread development.

Http://marshal.easymorse.com/archives/4519





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.