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.

Multithreading 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 Medium, Apple Provided Nsoperation This class provides an excellent multi-threaded programming method.
This introduction Nsoperation Subset of, Simple Method Nsinvocationoperation :
@ Implementation mycustomclass
-(Void) launchtaskwithdata :( ID) data
{
// Create Nsinvocationoperation Object and initialize it to the Method
// Here, Selector The value after the parameter is the method (function, Method )
// Here, Object The value is the data to be passed to the previous method.
Nsinvocationoperation * theop = [[nsinvocationoperation alloc] initwithtarget: Self
Selector: @ selector (mytaskmethod :) object: Data];
 
// Next we will create an operation "Operation" Add to localProgram(The method will be executed immediately after being added)
// In more cases, we will build our own " Operation " Queue
[[Myappdelegate implements doperationqueue] addoperation: theop];
}
 
// This is actually running in another thread " Method "
-(Void) mytaskmethod :( ID) data
{
// Perform the task.
}
 
@ End One Nsoperationqueue An 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 operation queue
[Operationqueue setmaxconcurrentoperationcount: 1];
// Only one thread is running in this queue.
// This queue is ready for use.
}
Return self;
}
 
-(Void) dealloc
{
[Operationqueue release];
// As Alan As we often say, We are good citizens 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, we only use multithreading to prevent the main thread from being congested. Nsinvocationoperation Is the simplest multi-threaded programming, in IPhone Programming is often used.

//////////////////////////////////////// //////////////////////////////////////// ///////////////////
1 Add Loading Image ......
2 {
3 [Window addsubview: view_loading];
4 [nsthread detachnewthreadselector: @ selector (init_backup :) totarget: Self withobject: Nil];
5}
You can use Performselectorohmainthread Update UI Elements, such as setting progress bars. Final elimination Loading Screen, load to the master 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}

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

ExploitationIPhoneMulti-thread implementation and thread synchronization

You can see from the interface definition that,NsthreadAnd mostIPhoneThere are two ways to initialize the same interface object:

One usageInitwithtarget :( ID) Target selector :( SEL) selector object :( ID) argumentBut is responsibleRetain countIs0When calling the objectReleaseMethod To clear objects.

The other uses the so-calledConvenient Method,This convenient interface isDetachnewthreadselectorThis 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 followingCode:
// 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 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];
}
@ End

Bytes -------------------------------------------------------------------------------------
//Definition
# 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 N To wait Thread , Set -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 (@ "
[_ mycondition lock];
while (_ threadcount <0) {
[_ mycondition Wait];
}
nslog (@ "
[_ mycondition unlock];
nslog (@ "
[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

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.