Early iOS multi-thread experience

Source: Internet
Author: User

IOS MultithreadingThe first experience is what we will introduce in this article.ThreadThe application is not uncontrolled. Official documents show thatThreadThe stack size of is 1 M, and the secondThreadAt the beginning, the data volume is kb. And the value cannot be switched through the compiler orThreadAPI function. Only MasterThreadAbility to 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.

 
 
  1.  self.queue = [[NSOperationQueue alloc] init];  
  2.     ArticleParseOperation *parser = [[ArticleParseOperation alloc] initWithData:filePath delegate:self];  
  3.     [queue addOperation:parser];  
  4.     [parser release];  
  5.  [queue release]; 

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

Ii. NSThread

1. 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; 

2. Thread Synchronization and lock

To 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

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

3. Thread Interaction

When 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:

 
 
  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 anything and call autorelease in the thread function, the following error will occur:

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

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

Summary:IOS MultithreadingI hope this article will help you with the introduction of the first experience.

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.