Multithreading for iOS

Source: Internet
Author: User

Deep Dive into IOS Multithreading
Nsthread

Luo chaohui (http://blog.csdn.net/kesalin

CC license. For more information, see Source


IOS supports multiple levels of multi-threaded programmingThe higher the level, the higher the abstraction level, and the more convenient it is to use. It is also the most recommended method for Apple. The following lists the multi-threaded programming paradigms supported by IOS from the abstraction level to the high:
1, thread;
2. Cocoa operations;
3. Grand Central Dispatch (GCD) (ios4 is supported)

The following describes the three different paradigms:
ThreadThese three paradigms are relatively low, but they are also the most responsible for use. You need to manage the thread lifecycle and synchronize threads by yourself. Threads share part of the memory space of the same application. They have the same access permissions to Data. You need to coordinate multiple threads to access the same data. The general practice is to lock the data before access, which leads to a certain performance overhead. In
In iOS, we can use multiple forms of thread:
Cocoa threads: Use nsthread or directly
Nsobject class method implements mselectorinbackground: withobject: to create a thread. If you choose thread to implement multithreading
Nsthread is a recommended method.
POSIX Threads: a multi-threaded Library Based on C language,

Cocoa operations are implemented based on obective-C. nsoperation class encapsulates the operations that users need to perform in an object-oriented manner. We only need to focus on what we need to do, you don't have to worry too much about thread management, synchronization, and other things, because nsoperation has encapsulated these things for us.
Nsoperation is an abstract base class. We must use its subclass. IOS provides two default implementations: nsinvocationoperation (call operation) and
Nsblockoperation (BLOCK statement operation ).

Grand Central Dispatch (GCD): Ios4 is supported.It provides some new features and runtime libraries to support multi-core parallel programming., Which has a higher focus: how
Improves the CPU efficiency.

With the overall framework above, we can clearly understand the levels of different methods and possible efficiency and convenience differences. Next we will take a look at the use of nsthread, including the creation, start, synchronization, communication and other related knowledge. These
Thread usage is very similar.

Thread creation and startup
Nsthread can be directly created in two ways:

1:

[Nsthreaddetachnewthreadselector: @ selector (mythreadmainmethod :) totarget: selfwithobject: Nil]; // detach: Separate

And

2:

Nsthread * mythread = [[nsthread alloc] initwithtarget: Self

Selector: @ selector (mythreadmainmethod :)
Object: Nil];
[Mythread start];

The difference between the two methods is:The previous call immediately creates a thread to do things.AndNextAlthough you
Alloc is also init, but until we manuallyCall start
The thread will be created only when the thread is started.
. ThisLatency implementationIt is useful in many resource-related areas. In the latter way, We can configure the thread before starting the thread, for example, setting
Stack size, thread priority.

There is also an indirect method, which is more convenient. We do not even need to explicitly write nsthread-related code. The nsobject class method is used to create a thread:
[Myobjperformselectorinbackground: @ selector (mythreadmainmethod) withobject: Nil];
The effect is the same as that of detachnewthreadselector: totarget: withobject: Of nsthread.

Thread Synchronization
The thread synchronization method is similar to that in other systems. We can use atomic operations, mutex (mutex), and lock.
IOS atomic operation functions start with osatomic, such as osatomicadd32 and osatomicor32. These functions can be used directly because they are atomic operations.

In iOS, mutex corresponds to nslock, which complies with the nslocking protocol., We can use
Lock, trylock, lockbeforedata: To lock and unlock with unlock. Example:
Bool moretodo = yes;
Nslock * thelock = [[nslock alloc] init];
...

While (moretodo)

{

/* Do another increment of calculation */
/* Until there's no more to do .*/

If ([thelock trylock])

{

/* Update display used by all threads .*/
[Thelock unlock];
}
}

We can use the command @ synchronized to simplify nslock usage, so that we don't have to show the code for creating nslock, locking and unlocking.
-(Void) mymethod :( ID) anobj
{
@ Synchronized(Anobj)// Synchronize
{
// Everything between the braces is protected bythe @ synchronized directive.
}
}
 
There are other lock objects, such as the loop lock nsrecursivelock, the conditional lock nsconditionlock, and the distributed lock nsdistributedlock. Here we will not discuss them one by one. Please refer to the official documents.

Sequence of synchronous execution with nscodition
Nscodition is a special type of lock that we can use to synchronize the sequence of Operation execution. The difference between it and mutex is that it is more accurate, waiting for a nscondtion
Until other threads send signals to the condition. The following is an example:

A thread is waiting for things to be done, and there is no things to be done by other threads to notify it.

[Cocoacondition lock];

While (timetodowork <= 0)

{

[Cocoacondition Wait];

}

 
Timetodowork --;
// Do real work here.
[Cocoacondition unlock];

Other threads can send signals to the above threads to do things:
[Cocoacondition lock];
Timetodowork ++;
[Cocoacondition signal];
[Cocoacondition unlock];

Inter-thread Communication
A thread may need to communicate with other threads during running. We can use some methods in nsobject:
Do things in the main thread of the application:
Performselectoronmainthread: withobject: waituntildone:
Performselecstmmainthread: withobject: waituntildone: modes:

Do things in the specified Thread:
Performselector: onthread: withobject: waituntildone:
Performselector: onthread: withobject: waituntildone: modes:

Do things in the current thread:
Optional mselector: withobject: afterdelay:
Optional mselector: withobject: afterdelay: inmodes:

Cancels a message sent to the current thread.
Cancelpreviousperformrequestswithtarget:
Cancelpreviousperformrequestswithtarget: selector: object:

For example, to download data in a thread and notify the main thread to update the interface after the download is complete, you can use the following interface:

-(Void) mythreadmainmethod

{
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
// To do something in your thread job
...
[Self?mselec=mainthread: @ selector (updateui) withobject: nilwaituntildone: No];
[Pool release];
}

 

Runloop
When it comes to nsthread, we can't help but talk about the closely related nsunloop.Run
Loop is equivalent to the Message Loop Mechanism in Win32.
It allows you to schedule the thread to be busy or idle Based on the event/message (mouse message, Keyboard Message, Timer message, etc.
The system automatically generates a corresponding run loop for the main thread of the application to process its message loop. When you touch uiview, the main thread of the application is in
In uiapplicationmain, such a run loop is used to distribute input or
Timer event.

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.