IPhone SDK multithreading usage and precautions

Source: Internet
Author: User

Multi-thread iPhone SDKThe usage and precautions are described in this article. If you do not need to talk about them, go to the topic. Although most PC applications currently supportMultithreading/Multi-task development method, but inIPhoneOn, Apple is not recommendedMultithreadingProgramming Method. HoweverMultithreadingAfter all, programming is a development trend and is said to be coming soon.IPhoneOS4 will be full

Although most PC applications currently supportMultithreading/Multi-task development method, but inIPhoneOn, Apple is not recommendedMultithreadingProgramming Method. HoweverMultithreadingAfter all, programming is a development trend and is said to be coming soon.IPhoneOS4 will be fully supportedMultithreading. So MasterMultithreadingProgramming method, in some cases can be dug outIPhoneGreater potential

Start with an example

Start with a routine. For more information about the code, see here. You can download other routines. For the control model of multi-threaded programs, see here. Generally, the manager/worker model is used. Here, we use NSThread in the iPhone SDK to implement it.

First, create a new View-based application project named "TutorialProject ". As shown in the interface, use UILabel to implement the two parts (Thread Part and Test Part). The Thread Part contains a UIProgressView and a UIButton. The Test Part contains a value and a UISlider.

Next, create IBOutlets for each UI control in the TutorialProjectViewController. h file.

 
 
  1. @interface TutorialProjectViewController : UIViewController {  
  2.     // ------ Tutorial code starts here ------  
  3.     // Thread part  
  4.     IBOutlet UILabel *threadValueLabel;  
  5.     IBOutlet UIProgressView *threadProgressView;  
  6.     IBOutlet UIButton *threadStartButton;  
  7.     // Test part  
  8.     IBOutlet UILabel *testValueLabel;  
  9.     // ------ Tutorial code ends here ------  

At the same time, you also need to create the property of the outlets variable.

 
 
  1. @property (nonatomic, retain) IBOutlet UILabel *threadValueLabel;  
  2. @property (nonatomic, retain) IBOutlet UIProgressView *threadProgressView;  
  3. @property (nonatomic, retain) IBOutlet UIProgressView *threadStartButton;  
  4. @property (nonatomic, retain) IBOutlet UILabel *testValueLabel; 

Next, define the action function when the button is pressed and the variable function of slider.

 
 
  1. -(IBAction) startThreadButtonPressed :( UIButton *) sender;
  2. -(IBAction) testValueSliderChanged :( UISlider *) sender;
  3. Then in the TutorialProjectViewController. m file synthesize outlets, and in the file to implement dealloc release resources.
  4. @ Synthesize threadValueLabel, threadProgressView, testValueLabel, threadStartButton;
  5. ...
  6. -(Void) dealloc {
  7. // ------ Tutorial code starts here ------
  8. [ThreadValueLabel release];
  9. [ThreadProgressView release];
  10. [ThreadStartButton release];
  11. [TestValueLabel release];
  12. // ------ Tutorial code ends here ------
  13. [Super dealloc];
  14. }

Start the code of the thread. First, when the thread button is pressed, create a new thread.

 
 
  1. - (IBAction) startThreadButtonPressed:(UIButton *)sender {  
  2.     threadStartButton.hidden = YES;  
  3.     threadValueLabel.text = @"0";  
  4.     threadProgressView.progress = 0.0;  
  5.     [NSThread detachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:self withObject:nil];  

After the button is pressed, hide the button to prevent multiple threads from being created. Initialize the display value and progress bar, and create a new thread. The thread function is startTheBackgroundJob. The specific startTheBackgroundJob function is defined as follows.

 
 
  1. -(Void) startTheBackgroundJob {
  2.  
  3. NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
  4. // Pause the thread for 3 seconds after it starts. Here, we only demonstrate the method for pausing the thread. You do not have to do this)
  5. [NSThread sleepForTimeInterval: 3];
  6. [Self defined mselecw.mainthread: @ selector (makeMyProgressBarMoving) withObject: nil waitUntilDone: NO];
  7. [Pool release];
  8. }

In row 3, An NSAID utoreleasepool object is created to manage the object Resources automatically released in the thread. Here, the NSAID utoreleasepool is released when the thread exits. This complies with the general rules of the Cocoa GUI application. The last line blocks the call to the waitUntilDone function. The status is ON.

 
 
  1. - (void)makeMyProgressBarMoving {  
  2.  
  3.     float actual = [threadProgressView progress];  
  4.     threadValueLabel.text = [NSString stringWithFormat:@"%.2f", actual];  
  5.     if (actual < 1) {  
  6.         threadProgressView.progress = actual + 0.01;  
  7.         [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];  
  8.     }  
  9.     else threadStartButton.hidden = NO;  

Calculate the value of the progress bar to be displayed. NSTimer increases by 0.5 every 0.01 seconds. When the value is equal to 1, the progress bar is 100%. Exit the function and display the hidden button.

Finally, add the UISlider implementation function to change the label value in the Test Part in the main thread.

 
 
  1. - (IBAction) testValueSliderChanged:(UISlider *)sender {  
  2. testValueLabel.text = [NSString stringWithFormat:@"%.2f", sender.value];  

Compile and execute the program. Press the thread start button and you will see that the progress bar is running in the background.

Thread usage considerations

Thread stack size

Application Development on iPhone devices is also the development of embedded devices. You also need to pay attention to several issues during development of embedded devices, such as resource ceiling and processor speed.

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.

You can use the following example to test your device. POSIX Threadpthread is used here. The device environment is iPhone 3GS (16 GB) and SDK is 3.1.3.

 
 
  1. #include "pthread.h"  
  2.  
  3. void *threadFunc(void *arg) {  
  4.     void*  stack_base = pthread_get_stackaddr_np(pthread_self());  
  5.     size_t stack_size = pthread_get_stacksize_np(pthread_self());  
  6.     NSLog(@"Thread: base:%p / size:%u", stack_base, stack_size);  
  7.     return NULL;  
  8. }  
  9.  
  10. - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  11.     void*  stack_base = pthread_get_stackaddr_np(pthread_self());  
  12.     size_t stack_size = pthread_get_stacksize_np(pthread_self());  
  13.     struct rlimit limit;  
  14.     getrlimit(RLIMIT_STACK, &limit);  
  15.     NSLog(@"Main thread: base:%p / size:%u", stack_base, stack_size);  
  16.     NSLog(@"  rlimit-> soft:%llu / hard:%llu", limit.rlim_cur, limit.rlim_max);  
  17.  
  18.     pthread_t thread;  
  19.     pthread_create(&thread, NULL, threadFunc, NULL);  
  20.  
  21.     // Override point for customization after app launch  
  22.     [window addSubview:viewController.view];  
  23.     [window makeKeyAndVisible];  

The result is as follows:

Simulator

 
 
  1. Main thread: base:0xc0000000 / size:524288  
  2. rlimit-> soft:8388608 / hard:67104768  
  3. Thread: base:0xb014b000 / size:524288 

Device

 
 
  1. Main thread: base:0x30000000 / size:524288  
  2. rlimit-> soft:1044480 / hard:1044480  
  3. Thread: base:0xf1000 / size:524288 

It can be seen that when you test a multi-threaded program, the stack size of the simulator is different from that of the actual device. Pay attention to calling a large number of recursive functions.

Autorelease

If you do not consider anything, call it in a thread function.Autorelease, The following error will occur:

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

Generally, the memory usage mode in the thread is that the thread initially

 
 
  1. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 

[Pool drain] or [pool release] at the end of the thread.

Child Line plotting window

In multi-threaded programming, a general principle is that all UI-related operations are performed by the main thread. The sub-thread is only responsible for transactions and data processing. How can I update the UI in a child thread? If it is in windows, you will post the message to describe the updated message. On the iPhone, you need to use the receivmselecdomainmainthread to delegate the main thread for processing.

For example, if you want to update the image of UIImageView in a child thread

 
 
  1. imageView.image = [UIImage imageNamed:@"Hoge.png"]; 

In this way, nothing will happen. You need to delegate the processing to the main thread, as shown below:

 
 
  1. [delegate performSelectorOnMainThread:@selector(theProcess:) withObject:nil waitUntilDone:YES]; 

OK!

Summary:IPhone SDKMediumMultithreadingI hope this article will be helpful to 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.