IOS supports multiple levels of multithreaded programming, the higher the level of abstraction, the more convenient to use, but also Apple's most recommended method. The following is a list of the multithreaded programming paradigms supported by iOS, from low to high, based on the level of abstraction:
1, Thread;
2, Cocoa operations;
3, Grand Central Dispatch (GCD) (iOS4 only start to support)
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 for the use, you need to manage the thread's life cycle, synchronization between threads. Threads share part of the memory space of the same application, and they have the same access rights to the data. You have to coordinate the access of multiple threads to the same data, and the general practice is to lock them before access, which can lead to some 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 a thread. If you choose thread to implement multi-threading, then nsthread is the preferred way to use the official recommendation.
POSIX Threads: A multi-line libraries based on the C language,
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 too much about thread management, synchronization, etc. 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.
Grand Central Dispatch (GCD): IOS4 only started to support, it provides some new features, and the 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 the
nsthread* myThread = [[Nsthread alloc] initwithtarget:self
selector: @selector (mythreadmainmethod:)
Object:nil];
[MyThread start];
The difference between the two approaches is that the first call creates a thread to do the work immediately, and the second one, although you alloc init, will not actually create the thread until we manually invoke start to start the thread. This idea of deferred implementation is useful in many resources-related areas. The latter way we can also configure the thread before starting the thread, such as setting the stack size, thread priority.
There is also an indirect way to be more convenient, and we don't even need to explicitly write Nsthread-related code. That is, using NSObject's class method, Performselectorinbackground:withobject: To create a thread:
[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];
}
}
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. It differs from a mutex in that it is more precise, waiting for a nscondtion thread to be locked until the other thread sends a signal to that condition. Let's look at the example using:
A thread waits for something to be done, and there is nothing to do that is notified by another thread.
[cocoacondition lock];
While (timetodowork <= 0)
[cocoacondition wait];
timetodowork--;
//Do real work here.
[cocoacondition unlock];
Other threads send a signal to notify the above thread that they can do things:
[cocoacondition lock];
timetodowork++;
[cocoacondition signal];
[cocoacondition unlock];
inter-thread communication
threads may need to communicate with other threads during the run. We can use some of the methods in NSObject:
do things in the main thread of the application:
PerformSelectorOnMainThread:withObject:waitUntilDone:
PerformSelectorOnMainThread:withObject:waitUntilDone:modes:
to do something in the specified thread:
PerformSelector:onThread:withObject:waitUntilDone:
PerformSelector:onThread:withObject:waitUntilDone:modes:
do things in the current thread:
PerformSelector:withObject:afterDelay:
PerformSelector:withObject:afterDelay:inModes:
cancels a message sent to the current thread
Cancelpreviousperformrequestswithtarget:
CancelPreviousPerformRequestsWithTarget:selector:object:
such as when we download data in a thread, after the download is complete to notify the main thread of the update interface, etc., 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 the main line of the application into a corresponding run loop to process its message loop. The ability to fire touchesbegan/touchesmoved and so on when touching UIView is called because the main thread of the application has such a run loop in the Uiapplicationmain that distributes input or timer Thing
Resources:
Nsrunloop Overview and principles:http://xubenyang.me/384
Official document: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/multithreading/
Reprint to:
http://blog.csdn.net/kesalin/article/details/6698146