Tutorial on iPhone multi-thread programming

Source: Internet
Author: User

IPhone MultithreadingThe Programming Tutorial is the content to be introduced in this article.MultithreadingSo this article can also be used as a reference for learning. Let's talk about it in detail.MultithreadingProgramming.

Multi-thread programming in iphone: thread Creation

MultithreadingIt is difficult to implement in many programming languages. Although objective-c originated from c, its multi-threaded programming is quite simple and comparable to java.

I. Thread creation and startup

There are two main ways to create a thread:

 
 
  1. - (id)init;     // designated initializer  
  2. - (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:

 
 
  1. + (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:

 
 
  1. - (void)start; 

Multi-thread programming in iphone: synchronization and lock of threads

DescriptionThreadThe best example of synchronization and lock is the ticketing 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. This is an example from the Internet:

SellTicketsAppDelegate. h file

 
 
  1. //  SellTicketsAppDelegate.h  
  2. import <UIKit/UIKit.h> 
  3.    
  4. @interface SellTicketsAppDelegate : NSObject <UIApplicationDelegate> {  
  5.      int tickets;  
  6.      int count;  
  7.      NSThread* ticketsThreadone;  
  8.      NSThread* ticketsThreadtwo;  
  9.      NSCondition* ticketsCondition;  
  10.      UIWindow *window;  
  11.  }  
  12. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  13. @end 

SellTicketsAppDelegate. m file

 
 
  1. // SellTicketsAppDelegate. m
  2. Import "SellTicketsAppDelegate. h"
  3. @ Implementation SellTicketsAppDelegate
  4. @ Synthesize window;
  5. -(Void) applicationDidFinishLaunching :( UIApplication *) application {
  6. Tickets = 100;
  7. Count = 0;
  8. // Lock Object
  9. TicketCondition = [[NSCondition alloc] init];
  10. TicketsThreadone = [[NSThread alloc] initWithTarget: self selector: @ selector (run) object: nil];
  11. [TicketsThreadone setName: @ "Thread-1"];
  12. [TicketsThreadone start];
  13. TicketsThreadtwo = [[NSThread alloc] initWithTarget: self selector: @ selector (run) object: nil];
  14. [TicketsThreadtwo setName: @ "Thread-2"];
  15. [TicketsThreadtwo start];
  16. // [NSThread detachNewThreadSelector: @ selector (run) toTarget: self withObject: nil];
  17. // Override point for customization after application launch
  18. [Window makeKeyAndVisible];
  19. }
  20. -(Void) run {
  21. While (TRUE ){
  22. // Lock
  23. [TicketsCondition lock];
  24. If (tickets> 0 ){
  25. [NSThread sleepForTimeInterval: 0.5];
  26. Count = 100-tickets;
  27. NSLog (@ "Current ticket count: % d, sold: % d, thread name: % @", tickets, count, [[NSThread currentThread] name]);
  28. Tickets --;
  29. } Else {
  30. Break;
  31. }
  32. [TicketsCondition unlock];
  33. }
  34. }
  35. -(Void) dealloc {
  36. [TicketsThreadone release];
  37. [TicketsThreadtwo release];
  38. [TicketsCondition release];
  39. [Window release];
  40. [Super dealloc];
  41. }
  42. @ End

Multi-thread programming in iphone: thread Interaction

ThreadDuring runningThreadFor communication, suchThreadYou can use the following interfaces:

 
 
  1. - (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:

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

If you do not consider anythingThreadIf autorelease is called in the function, the following error occurs:

 
 
  1. NSAutoReleaseNoPool(): Object 0x********* of class NSConreteData autoreleased with no pool in place …. 

Summary: AboutIPhone MultithreadingThe content of the Programming Tutorial is complete. I hope this article will help you!

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.