iOS development: Multithreading Nsthread and Nsinvocationoperation

Source: Internet
Author: User
Tags thread uikit

Multithreaded programming is the best way to prevent the main thread from clogging, increasing the efficiency of running, and so on. But the original multithreading method has many problems, including the thread lock Deng. In cocoa, Apple provides a nsoperation class that provides an excellent multithreaded programming approach.

This article introduces the subset of Nsoperation, the simple method of nsinvocationoperation:

@implementation MyCustomClass

-(void) Launchtaskwithdata: (ID) data

{

Creates a Nsinvocationoperation object and initializes it to the method;

Here, the value after the selector parameter is the method you want to run in another thread (function, methods);

Here, the value after object is the data that you want to pass to the previous method

Nsinvocationoperation *theop = [nsinvocationoperation alloc]initwithtarget:self selector: @selector (mytashmethod:) Object:data];

The operation "Operation" We have established is added to the Shared queue of the local program (the method will be executed immediately upon accession)

More often, we build our own "operations" queues.

[[Myappdelegate Sharedoperationqueue] addoperation:theop];

}

This is the "method" that really runs on another thread

-(void) Mytaskmethod: (ID) data

{

Perform the task.

}

@end

A nsoperationqueue operation queue is equivalent to a thread manager, not a thread. Because you can set the number of threads in this thread manager that can run in parallel, and so on.

The following is the establishment and initialization of an action queue:

@interface Myviewcontroller:uiviewcontroller {

Nsoperationqueue* Operationqueue;

Declaring the queue in a header file

}

@end

@implementation Myviewcontroller

-(ID) init

{

self = [super init];

if (self) {

Initializing an action queue

Operationqueue = [[Nsoperationqueue alloc] init];

[Operationqueue setmaxconcurrentoperationcount:1];

The queue is limited here to run only one thread at a time

This queue is ready to use.

}

return self;

}

-(void) dealloc

{

[Operationqueue release];

[Super Dealloc];

}

@end

After a brief introduction, you can actually find this method is very simple. Many times we use multithreading just to prevent the main thread from clogging, and nsinvocationoperation is the simplest multithreaded programming that is often used in iphone programming.

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

In the main line Chengri add a loading screen ...

{

[Window addsubview:view_loading];

Another new thread, which may take time for background processing, is to prevent the main program from waiting at this time, to place the background processing in a thread that is not in the primary thread, and to notify the main thread to update the data after execution.

[Nsthread detachnewthreadselector: @selector:(init_backup:) totarget:self Withobject:nil];

}

You can update UI elements by Performselectorohmainthread, such as setting progress bars, and so on. Finally eliminate the loading screen, load into the main view.

-(void) Init_backup: (ID) sender

{

nsautorelease* pool = [[NSAutoreleasePool alloc] init];

The newly created thread requires an automatic free pool to manage the memory requested in the thread

int i = status;

[Self performselectoronmainthread: @selector:(show_loading:) wiwithobject::[nsnumber numberwithint:i] WaitUntil done : NO];

[View_loading Removefromsuperview];

[Window AddSubview:tabcontroller_main.view];

[Pool release];

}

Using the iphone's multi-threaded implementation and thread synchronization

As you can see from the definition of interfaces, Nsthread, like most iphone interface objects, can be initialized in two ways:

One uses the Initwithtarget:(ID) target selector: (SEL) Selector object: (ID) argument, but takes responsibility for the retain Count is 0 o'clock to call the object's release method to clean the object.

The other uses the so-called convenient method, which is detachnewthreadselector, which generates a thread directly and starts it without being responsible for thread cleanup.

#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

#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) {

Locked

[Ticketscondition Lock];

if (Tickets > 0)

{

[Nsthread sleepfortimeinterval:0.5];

Count = 100-tickets;

NSLog (@ "The current number of votes is:%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];

}

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.