iOS development: Multithreaded programming Nsthread use of the detailed

Source: Internet
Author: User
Tags gcd instance method ticket

1. Brief Introduction:

1.1 iOS has three kinds of multithreaded programming technology, namely:

1., Nsthread

2, Cocoa Nsoperation (iOS multithreaded programming nsoperation and the use of Nsoperationqueue)

3, GCD full name: Grand Dispatch (iOS multithreaded Programming Grand Dispatch (GCD) Introduction and use)

These three programming methods from top to bottom, the abstraction level is from low to high, the higher the abstraction of the use of the more simple, is Apple's most recommended use.

This article we mainly introduce and use the Nsthread, will continue to 2, 3 of the explanation and use.

1.2 Three ways to introduce the advantages and disadvantages:

Nsthread:

Advantages: Nsthread is lighter than the other two

Disadvantage: You need to manage the lifecycle of your threads and thread synchronization. Thread synchronization has a certain overhead for locking data

The technology implemented by Nsthread has the following three kinds:

General use of cocoa thread technology.

Cocoa operation

Advantages: No need to care about thread management, data synchronization, you can focus on what you need to do.

Cocoa operation related classes are nsoperation, Nsoperationqueue. Nsoperation is an abstract class that uses its subclasses to implement it or to use it to define two subclasses: Nsinvocationoperation and Nsblockoperation. Creates an object of the Nsoperation subclass and adds the object to the Nsoperationqueue queue for execution.

GCD

Grand-Dispatch (GCD) is a solution for multi-core programming developed by Apple. Can be used only after iOS4.0 has started. GCD is an efficient and powerful technology that replaces technologies such as Nsthread, Nsoperationqueue, and Nsinvocationoperation. Today's iOS systems are upgraded to 6, so don't worry about the technology being used.

After introducing these three kinds of multithreaded programming methods, we introduce the use of Nsthread first.

2, the use of Nsthread

There are two direct ways to create 2.1 Nsthread:

-(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument

+ (void) Detachnewthreadselector: (SEL) Aselector totarget: (ID) atarget withobject: (ID) anargument

The first is the instance method, and the second is the class method

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

nsthread* mythread = [[Nsthread alloc] initwithtarget:self selector: @selector (dosomething:) Object:nil];

[Mythread start];

2.2 The meaning of the parameter:

Selector: The method that the thread executes, the selector can have only one parameter and cannot have a return value.

Target:selector the object sent by the message

Argument: The only parameter that is transmitted to target, or it can be nil

The first way is to create the thread directly and start running the thread, the second way is to create the thread object, and then run the thread operation, you can set the thread's priority before running the thread, such as thread information

2.3 PS: A method that does not explicitly create a thread:

NSObject class method Performselectorinbackground:withobject: Create a thread:

[OBJ performselectorinbackground: @selector (dosomething) Withobject:nil];

2.4 Examples of downloading pictures:

2.4.1 New Singeview App

Creates a new project and places a ImageView control on the Xib file. Hold down the control key and drag into the ViewController.h file to create the ImageView iboutlet viewcontroller.m:

Viewcontroller.m

Nsthreaddemo

//

Created by Rongfzh on 12-9-23.

Copyright (c) 2012 Rongfzh. All rights reserved.

//

#import "ViewController.h"

#define KURL @ "Http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"

@interface Viewcontroller ()

@end

@implementation Viewcontroller

d) Downloadimage: (NSString *) url{

NSData *data = [[NSData alloc] Initwithcontentsofurl:[nsurl Urlwithstring:url]];

UIImage *image = [[UIImage alloc]initwithdata:data];

if (image = = nil) {

}else{

[Self Performselectoronmainthread: @selector (updateui:) withobject:image Waituntildone:yes];

}

}

d) UpdateUI: (uiimage*) image{

Self.imageView.image = image;

}

-(void) viewdidload

{

[Super Viewdidload];

[Nsthread detachnewthreadselector: @selector (downloadimage:) totarget:self Withobject:kurl];

Nsthread *thread = [[Nsthread alloc]initwithtarget:self selector: @selector (downloadimage:) Object:kurl];

[Thread start];

}

-(void) didreceivememorywarning

{

[Super didreceivememorywarning];

Dispose of any of the can is recreated.

}

@end

2.4.2 Communication between threads

How do I inform the main thread update interface after the thread downloads the picture?

[Selfperformselectoronmainthread: @selector (updateui:) withobject:image Waituntildone:yes];

Performselectoronmainthread is a NSObject method, in addition to updating the main thread's data, you can update other threads such as:

Used: PerformSelector:onThread:withObject:waitUntilDone:

To run the download Picture:

The picture is downloaded.

2.3 Thread Sync

We demonstrate a classic ticket-selling example for Nsthread thread synchronization:

. h

#import

@class Viewcontroller;

@interface Appdelegate:uiresponder

{

int tickets;

int count;

nsthread* Ticketsthreadone;

nsthread* Ticketsthreadtwo;

nscondition* ticketscondition;

Nslock *thelock;

}

@property (Strong, nonatomic) UIWindow *window;

@property (Strong, nonatomic) Viewcontroller *viewcontroller;

@end

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions

{

Tickets = 100;

Count = 0;

Thelock = [[Nslock alloc] init];

Lock Object

Ticketscondition = [[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];

Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]];

Override point for customization after application launch.

Self.viewcontroller = [[Viewcontroller alloc] initwithnibname:@ "Viewcontroller" bundle:nil];

Self.window.rootViewController = Self.viewcontroller;

[Self.window makekeyandvisible];

return YES;

}

-(void) run{

while (TRUE) {

Locked

[Ticketscondition Lock];

[Thelock Lock];

if (tickets >= 0) {

[Nsthread sleepfortimeinterval:0.09];

Count = 100-tickets;

NSLog (@ "The current number of votes is:%d, sold:%d, thread name:%@", Tickets,count,[[nsthread CurrentThread] name));

tickets--;

}else{

Break

}

[Thelock unlock];

[Ticketscondition unlock];

}

}

If there is no thread sync lock, the ticket count may be-1. The thread synchronization guarantees the correctness of the data after the lock is added.

In the example above I used two kinds of locks, one nscondition, one is: Nslock. Nscondition I have commented on it.

Sequential execution of threads

They can all pass

[Ticketsconditionsignal]; Send a signal in a way that wakes up another thread in a thread waiting.

Like what:

#import "AppDelegate.h"

#import "ViewController.h"

@implementation Appdelegate

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions

{

Tickets = 100;

Count = 0;

Thelock = [[Nslock alloc] init];

Lock Object

Ticketscondition = [[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 *ticketsthreadthree = [[Nsthread alloc] initwithtarget:self selector: @selector (RUN3) Object:nil];

[Ticketsthreadthree setname:@ "Thread-3"];

[Ticketsthreadthree start];

Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]];

Override point for customization after application launch.

Self.viewcontroller = [[Viewcontroller alloc] initwithnibname:@ "Viewcontroller" bundle:nil];

Self.window.rootViewController = Self.viewcontroller;

[Self.window makekeyandvisible];

return YES;

}

-(void) run3{

while (YES) {

[Ticketscondition Lock];

[Nsthread Sleepfortimeinterval:3];

[Ticketscondition signal];

[Ticketscondition unlock];

}

}

-(void) run{

while (TRUE) {

Locked

[Ticketscondition Lock];

[Ticketscondition wait];

[Thelock Lock];

if (tickets >= 0) {

[Nsthread sleepfortimeinterval:0.09];

Count = 100-tickets;

NSLog (@ "The current number of votes is:%d, sold:%d, thread name:%@", Tickets,count,[[nsthread CurrentThread] name));

tickets--;

}else{

Break

}

[Thelock unlock];

[Ticketscondition unlock];

}

}

Wait is waiting, I added a thread 3 to wake up the other two threads in the lock

Other sync

We can use instruction @synchronized to simplify the use of nslock so that we do not have to display the write creation Nslock, lock and unlock the relevant code.

-(void) DoSomething: (ID) anobj

{

@synchronized (Anobj)

{

Everything between the braces is protected by the@synchronizeddirective.

}

}

There are other lock objects, such as: Loop lock Nsrecursivelock, conditional lock nsconditionlock, distributed lock Nsdistributedlock and so on, you can see the Official document learning

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.