Detailed explanation of iOS multithreading, detailed explanation of ios multithreading Reprinting

Source: Internet
Author: User

Detailed explanation of iOS multithreading (reprinting), detailed explanation of ios multithreading Reprinting
The thread application in the iPhone is not uncontrolled. Official documents show that the stack size of the main thread in the iPhone OS is 1 MB, and that of the second thread is kb at the beginning. The value cannot be changed through the compiler switch or the thread API function.

Only the main thread can directly modify the UI.

I. NSOperation and NSOperationQueue

1. An operation class inherited from NSOperation. The implementation of this class must contain the-(void) main method.

2. The simplest way to use NSOperation is to put it into NSOperationQueue.

Once an operation is added to the queue, the queue starts and starts to process it (that is, the main method of the operation class is called ). Once this operation is completed, the queue will release it.

<Style> <! -- P. p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: # 7e1aad} p. p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #428288} p. p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: # 265a5e} p. p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo} p. p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #490085} span. s1 {color: # cb00a5} span. s2 {color: #000000} span. s3 {color: #428288} span. s4 {color: #490085} span. s5 {color: # 7e1aad} span. s6 {color: # 265a5e} span. s7 {color: # e00005} span. apple-tab-span {white-space: pre} --> </style>

Self. queue = [[NSOperationQueuealloc] init];

ArticleParseOperation * parser = [[ArticleParseOperationalloc] initWithData: filePathdelegate: self];

[Queue addOperation: parser];

[Parser release];

[Queuerelease];

3. You can set the maximum number of operations in the Operation queue: [queue setMaxConcurrentOperationCount: 2];

Ii. NSThread <>

I. Thread creation and startupThere are two main ways to create a thread:

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

Of course, there is another special kind, that is, the so-called convenient method, which can directly generate a thread and start it, without being responsible for thread cleaning. The interface for this method is:

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

After the first two methods are created, the mobile phone needs to be started. The start method is as follows:

- (void)start;

Ii. Synchronization and lock of threadsTo describe the synchronization and lock of threads, the best example may be the ticket sales system with multiple windows at the same time. 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. This is an example from the Internet: SellTicketsAppDelegate. h file

//  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

SellTicketsAppDelegate. m 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

3. Thread InteractionWhen a thread is running, it may need to communicate with other threads, such as modifying the interface in the main thread. You can use the following interface:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

Because some resources may need to be released during this process, you need to use the NSAID utoreleasepool for management, such:

- (void)startTheBackgroundJob {    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    // to do something in your thread job    ...    [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];    [pool release];}

If you do not consider anything and call autorelease in the thread function, the following error will occur:NSAutoReleaseNoPool(): Object 0x********* of class NSConreteData autoreleased with no pool in place ….

4. For more information about the thread pool, see NSOperation.

Original: http://www.voland.com.cn/iphone-in-the-multi-threaded-programming

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.