Use of multiple threads for iphone

Source: Internet
Author: User

The following are some of the information collected at the initial stage of development, which is simple and practical. I hope to help new users. They are collected on the Internet. The original source is unknown. If you infringe your rights and interests, please inform us, I will delete the relevant content in time.

 

Multi-thread NSInvocationOperation

Multi-threaded programming is the best way to prevent the main thread from being congested and increase the running efficiency. The original multi-threaded method has many problems, including thread locking. In Cocoa, Apple provides the NSOperation class and an excellent multi-threaded programming method.

This section describes the subset of NSOperation and NSInvocationOperation of the simple method:

@ Implementation MyCustomClass

-(Void) launchTaskWithData :( id) data

{

// Create an NSInvocationOperation object and initialize it to the Method

// Here, the value after the selector parameter is the Method (function, Method) You want to run in another thread)

// Here, the object value is the data to be passed to the previous method.

NSInvocationOperation * theOp = [[NSInvocationOperation alloc] initWithTarget: self

Selector: @ selector (myTaskMethod :) object: data];

 

// Add the Operation "Operation" we created to the shared queue of the local program (the method will be executed immediately after the Operation is added)

// In more cases, we create an "operation" queue by ourselves.

[[MyAppDelegate implements doperationqueue] addOperation: theOp];

}

 

// This is the "method" that actually runs in another thread"

-(Void) myTaskMethod :( id) data

{

// Perform the task.

}

 

@ End an NSOperationQueue operation queue is equivalent to a thread manager rather than a thread. Because you can set the number of threads that can run in parallel in this thread manager. The following describes how to create and initialize an operation queue:

 

@ Interface MyViewController: UIViewController {

 

NSOperationQueue * operationQueue;

// Declare the queue in the header file

}

@ End

 

@ Implementation MyViewController

 

-(Id) init

{

Self = [super init];

If (self ){

OperationQueue = [[NSOperationQueue alloc] init]; // initialize the operation queue

[OperationQueue setMaxConcurrentOperationCount: 1];

// This limits the queue to run only one thread at a time

// This queue is ready for use.

}

Return self;

}

 

-(Void) dealloc

{

[OperationQueue release];

// As Alan often said, we are a good citizen of the program and need to release the memory!

[Super dealloc];

}

 

@ End after a brief introduction, we can find that this method is very simple. In many cases, multithreading is only used to prevent main thread congestion, and NSInvocationOperation is the simplest multi-threaded programming, which is often used in iPhone programming.

 

 

 

//////////////////////////////////////// //////////////////////////////////////// ///////////////////

1. Add a loading screen to the main thread ......

2 {

3 [window addSubview: view_loading];

4 [NSThread detachNewThreadSelector: @ selector (init_backup :) toTarget: self withObject: nil];

5}

You can use javasmselectorohmainthread to update UI elements, such as setting progress bars. Finally, the loading screen is eliminated and loaded into the main View.

7-(void) init_backup :( id) sender

8 {

9 NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];

10

11 //...

12 int I = status;

13 [self defined mselecw.mainthread: @ selector (show_loading :) withObject: [NSNumber numberWithInt: I] waitUntil Done: NO];

14

15 [view_loading removeFromSuperview];

16 [window addSubview: tabcontroller_main.view];

17 [pool release];

18}

 

//////////////////////////////////////// ///////////////

 

Multi-thread implementation and thread synchronization using iphone

 

From the interface definition, we can know that NSThread and most iphone interface objects are the same, there are two ways to initialize:

 

One method is to use initWithTargetid) target selector :( SEL) selector object :( id) argument, but to call the release method of the object to clear the object when the retain count of the object is 0.

 

The other method uses the so-called convenient method. This convenient interface is detachNewThreadSelector. This method can directly generate a thread and start it, without being responsible for thread cleaning.

 

# Import <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

 

Then add the following code in the implementation:

// SellTicketsAppDelegate. m

// SellTickets

//

// Created by sun dfsun2009 on 09-11-10.

// Copyright _ MyCompanyName _ 2009. All rights reserved.

//

# Import "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];

[TicketsThreadone setName: @ "Thread-1"];

[TicketsThreadone start];

TicketsThreadtwo = [[NSThread alloc] initWithTarget: self selector: @ selector (run) object: nil];

[TicketsThreadtwo 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

 

Bytes -------------------------------------------------------------------------------------

// Define

# Import <UIKit/UIKit. h>

 

@ Interface ThreadSyncSampleViewController: UIViewController {

Int _ threadCount;

NSCondition * _ myCondition;

}

 

@ End

 

// The implementation file is as follows:

 

# Import "ThreadSyncSampleViewController. h"

 

@ Implementation ThreadSyncSampleViewController

 

/*

// The designated initializer. Override to perform setup that is required before the view is loaded.

-(Id) initWithNibName :( NSString *) nibNameOrNil bundle :( NSBundle *) nibBundleOrNil {

If (self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil]) {

// Custom initialization

}

Return self;

}

*/

 

/*

// Implement loadView to create a view hierarchy programmatically, without using a nib.

-(Void) loadView {

}

*/

 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

-(Void) viewDidLoad {

[Super viewDidLoad];

//

// _ MyCondition = nil;

//

_ MyCondition = [[NSCondition alloc] init];

//

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 30

Target: self

Selector: @ selector (threadTester)

UserInfo: nil

Repeats: YES];

[Timer fire];

 

}

 

 

-(Void) threadTester {

[_ MyCondition lock];

 

_ ThreadCount =-2;

// If there are n threads to wait, set them to-n.

[_ MyCondition unlock];

//

NSLog (@"");

NSLog (@"------------------------------------------------------------------------------");

[NSThread detachNewThreadSelector: @ selector (threadOne) toTarget: self withObject: nil];

[NSThread detachNewThreadSelector: @ selector (threadTwo) toTarget: self withObject: nil];

[NSThread detachNewThreadSelector: @ selector (threadThree) toTarget: self withObject: nil];

Return;

}

 

-(Void) threadOne {

NSLog (@ "@ In thread 111111 start .");

[_ MyCondition lock];

 

Int n = rand () % 5 + 1;

NSLog (@ "@ Thread 111111 Will sleep % d seconds, now _ threadCount is: % d", n, _ threadCount );

Sleep (n );

// [NSThread sleepForTimeInterval: n];

_ ThreadCount ++;

NSLog (@ "@ Thread 111111 has sleep % d seconds, now _ threadCount is: % d", n, _ threadCount );

[_ MyCondition signal];

NSLog (@ "@ Thread 1111111 has signaled, now _ threadCount is: % d", _ threadCount );

[_ MyCondition unlock];

NSLog (@ "@ In thread one complete .");

[NSThread exit];

Return;

}

 

-(Void) threadTwo {

NSLog (@ "### In thread 2222222 start .");

[_ MyCondition lock];

 

Int n = rand () % 5 + 1;

NSLog (@ "### Thread 2222222 Will sleep % d seconds, now _ threadCount is: % d", n, _ threadCount );

Sleep (n );

// [NSThread sleepForTimeInterval: n];

_ ThreadCount ++;

NSLog (@ "### Thread 2222222 has sleep % d seconds, now _ threadCount is: % d", n, _ threadCount );

[_ MyCondition signal];

NSLog (@ "### Thread 2222222 has signaled, now _ threadCount is: % d", _ threadCount );

[_ MyCondition unlock];

// _ ThreadCount ++;

NSLog (@ "### In thread 2222222 complete .");

[NSThread exit];

Return;

}

 

-(Void) threadThree {

NSLog (@ "<In thread 333333 start .");

[_ MyCondition lock];

While (_ threadCount <0 ){

[_ MyCondition wait];

}

NSLog (@ "<In thread 333333, _ threadCount now is % d, will start work.", _ threadCount );

[_ MyCondition unlock];

NSLog (@ "<In thread 333333 complete .");

[NSThread exit];

Return;

}

 

/*

// Override to allow orientations other than the default portrait orientation.

-(BOOL) shouldAutorotateToInterfaceOrientation :( UIInterfaceOrientation) interfaceOrientation {

// Return YES for supported orientations

Return (interfaceOrientation = UIInterfaceOrientationPortrait );

}

*/

 

-(Void) didReceiveMemoryWarning {

// Releases the view if it doesn't have a superview.

[Super didReceiveMemoryWarning];

 

// Release any cached data, images, etc that aren't in use.

}

 

-(Void) viewDidUnload {

// Release any retained subviews of the main view.

// E.g. self. myOutlet = nil;

}

 

 

-(Void) dealloc {

[_ MyCondition release];

[Super dealloc];

}

 

@ End

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.