http://www.cocoachina.com/bbs/read.php?tid=43852
The OS supports multiple levels of multi-ThreadsProgramming, the higher the level of abstraction, the more convenient to use, but also the most recommended way to use Apple.
The following is a brief description of these three different paradigms:
Thread is relatively lightweight in these three paradigms, but is also the most responsible use, you need to manage the life cycle of thread,Threadssynchronization between the.ThreadsShare part of the memory space of the same application, which has the same access rights to the data.
You have to coordinate multipleThreadsAccess to the same data is generally done by locking before access, which results in a certain performance overhead. In IOS we can use several forms of thread:
Cocoa Threads: Use Nsthread or directly from the NSObject class method Performselectorinbackground:withobject: To create aThreads。 If you choose thread to implement multipleThreads, then Nsthread is the preferred way of official recommendation.
POSIX Threads: A multi-based C languageThreadsLibrary
Cocoa operations is implemented based on OBECTIVE-C, and class nsoperation encapsulates what the user needs to do in an object-oriented manner, so we focus on what we need to do, without worrying about it.ThreadsThe management, synchronization and other things,
Because Nsoperation has encapsulated these things for us. Nsoperation is an abstract base class, and we must use its subclasses. Two default implementations of IOS are available: Nsinvocationoperation and nsblockoperation.
The Grand central Dispatch:ios4 only started to support it, providing some new features, as well as a runtime to support multicore parallel programming, with a higher focus: how to increase efficiency on multiple CPUs.
With the overall framework above, we can clearly know the level of different ways and the possible efficiency, convenience differences. Let's take a look at the use of nsthread, including the creation, startup, synchronization, communication and other related knowledge. These are very similar to the thread usage under Win32/java.
thread creation and startup
There are two direct ways to create Nsthread:
[Nsthread detachnewthreadselector: @selector (mythreadmainmethod:) totarget:self Withobject:nil];
And
nsthread* myThread = [[Nsthread alloc] Initwithtarget:self
Selector: @selector (mythreadmainmethod:)
Object:nil];
[MyThread start];
The difference between the two approaches is that the previous invocation immediately creates aThreadsTo do things, and then, although you alloc, Init, but until we manually call startThreadsWhen you actually create it.Threads。
This idea of deferred implementation is useful in many resources-related areas. The latter way we can also startThreadsBefore, theThreadsConfiguration, such as setting the stack size,ThreadsPriority level.
There is also an indirect way to be more convenient, and we don't even need to explicitly write Nsthread-related code. That is to use NSObject's class method Performselectorinbackground:withobject: To create aThreads:
[MYOBJ performselectorinbackground: @selector (Mythreadmainmethod) Withobject:nil];
The effect is the same as Nsthread's detachNewThreadSelector:toTarget:withObject: the same.
thread synchronization
thread synchronization method is similar to other systems, we can use atomic operation, can use Mutex,lock and so on.
iOS's atomic manipulation functions start with osatomic, such as: OSAtomicAdd32, OSAtomicOr32, and so on. These functions can be used directly, as they are atomic operations.
The mutex in iOS corresponds to Nslock, which follows the nslooking protocol, and we can use lock, Trylock, Lockbeforedata: To lock and unlock with unlock. Examples of Use:
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];
}
}
Lock blocking wait
Trylock non-blocking
We can use the instruction @synchronized to simplify the use of nslock so that we do not have to display write create Nslock, lock and unlock related code.
-(void) MyMethod: (ID) anobj
{
@synchronized (Anobj)
{
Everything between the braces is protected by the @synchronized directive.
}
}
There are other lock objects, such as: Circular lock nsrecursivelock, conditional lock nsconditionlock, distributed lock Nsdistributedlock and so on, here is not introduced, everyone to see the official documents it.
order of execution with nscodition synchronization
Nscodition is a special type of lock that we can use to synchronize the order in which operations are performed. The difference between it and a mutex is that it is more precise, waiting for a nscondtionThreadshas been lock until the otherThreadsSent a signal to the condition.
Let's take a look at the use example: aThreadsWaiting for things to be done while there is nothing to do is made by otherThreadsNotified of it.
[Cocoacondition Lock];
while (timetodowork <= 0)
[Cocoacondition wait];
timetodowork--;
Do real work here.
[Cocoacondition unlock];
OtherThreadsSend a signal to notify the aboveThreadsCan do things:
[Cocoacondition Lock];
timetodowork++;
[Cocoacondition signal];
[Cocoacondition unlock];
inter- thread communication
ThreadsDuring the operation, you may need to work with otherThreadsfor communication. We can use some of the methods in NSObject:
In the application masterThreadsDo things in:
PerformSelectorOnMainThread:withObject:waitUntilDone:
PerformSelectorOnMainThread:withObject:waitUntilDone:modes:
In the specifiedThreadsDo things in:
PerformSelector:onThread:withObject:waitUntilDone:
PerformSelector:onThread:withObject:waitUntilDone:modes:
In the currentThreadsDo things in:
PerformSelector:withObject:afterDelay:
PerformSelector:withObject:afterDelay:inModes:
Cancel Send to currentThreadsOne of the messages
Cancelpreviousperformrequestswithtarget:
CancelPreviousPerformRequestsWithTarget:selector:object:
is the deferred function that cancels execution, like [self performselector: @selector (sendtest) withobject:nilafterdelay:10.0];
-(void) Networkreachabilitydidupdate: (networkreachability*) reachability
{
[nsobject cancelpreviousperformrequestswithtarget:self selector:@selector( Reachabilitychanged) object:nil];
[self performselector:@selector(reachabilitychanged) withobject:nil Afterdelay :0.1f];
}
Cancelpreviousperformrequestswithtarget is the delay call that terminates the last Performselector
The above example is to prevent repeated calls to reachabilitychanged within Afterdelay time
such as when we download data in a thread , to notify the main thread of the update interface after the download is complete, and so on, you can use the following interface:
-(void) Mythreadmainmethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
To does something in your thread job
...
[Self Performselectoronmainthread: @selector (UpdateUI) Withobject:nil Waituntildone:no];
[Pool release];
}
runloop
When it comes to nsthread, we cannot but talk about the nsrunloop with which the relationship is very close. The Run loop is equivalent to the message loop mechanism inside the Win32, which allows you to schedule whether a thread is busy or idle based on events/messages (mouse messages, keyboard messages, timer messages, etc.).
The system automatically generates a corresponding run loop for the application's main thread to process its message loop. The ability to excite touchesbegan/touchesmoved and so on when touching UIView is called,
This is because the main thread of the application has a run loop in Uiapplicationmain that distributes input or timer events.
[iOS] multi-threading Nsthread for iOS in layman's