How to program multiple threads in iphone

Source: Internet
Author: User

 

Multithreading is difficult in a variety of programming languages and is difficult to implement in many languages. Although objective-c originated from c, its multi-threaded programming is quite simple and comparable to java. This article briefly introduces the multi-thread programming in iphone from four aspects: thread creation and startup, thread synchronization and lock, thread interaction, and thread pool.

I. Thread creation and startup

There 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 also a special way to use the so-called convenient method, this method 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) after the first two methods of anArgument are created, the mobile phone needs to be started. The start method is:

-(Void) start;

Ii. Synchronization and lock of threads

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

// SellTicketsAppDelegate. h

Import

@ Interface SellTicketsAppDelegate: NSObject {

Int tickets;

Int count;

NSThread * ticketsThreadone;

NSThread * ticketsThreadtwo;

NSCondition * ticketsCondition;

UIWindow * window;

}

@ Property (nonatomic, retain) IBOutlet UIWindow * window;

@ End

SellTicketsAppDelegate. m file

// SellTicketsAppDelegate. m

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

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:

-(Void) specified mselecw.mainthread :( 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 {

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

// To do something in your thread job

...

[Self defined mselecw.mainthread: @ 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:

NSAID utoreleasenopool (): Object 0x ********* of class NSConreteData autoreleased with no pool in place ....

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

 

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.