[IOS] multi-thread NSThread for iOS, nsthread for ios development

Source: Internet
Author: User

[IOS] multi-thread NSThread for iOS, nsthread for ios development
[IOS] multi-thread NSThread for iOS

OS supports multiple levelsThreadProgramming, the higher the level of abstraction, the more convenient to use, is also Apple's most recommended method.
 
 
The following describes the three different paradigms:
Thread is relatively lightweight among the three paradigms, but it is also the most responsible for use. You need to manage the thread lifecycle by yourself,Thread.ThreadShares part of the memory space of the same application. They have the same access permissions to Data.
You have to coordinate multipleThreadThe general practice of accessing the same data is to lock the data before access, which leads to a certain performance overhead. In iOS, we can use multiple forms of thread:
Cocoa threads: Use NSThread or use the NSObject class method performSelectorInBackground: withObject: to createThread. If you choose thread to implement multipleThreadNSThread is the preferred method officially recommended.
POSIX threads: multiple threads in C LanguageThreadLibrary,
 
Cocoa operati ***** is implemented based on Obective-C. Class NSOperation encapsulates the operations that users need to perform in an object-oriented manner. We only need to focus on what we need to do, don't worry too muchThreadManagement, synchronization, and other things,
Because NSOperation already encapsulates these things for us. NSOperation is an abstract base class. We must use its subclass. IOS provides two default implementations: NSInvocationOperation and NSBlockOperation.
 
Grand Central Dispatch: iOS4 is supported. It provides some new features and runtime libraries to support multi-core parallel programming. It focuses more on how to improve efficiency on multiple CPUs.
 
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 are very similar to the thread usage in win32/Java.
 
ThreadCreate and start
NSThread can be directly created in two ways:
[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 methods is that the previous call will immediately createThreadThe next method, though alloc is also init, must be manually called to startThreadWill actually createThread.
This delay implementation idea is useful in many resource-related aspects. You can also startThreadPreviouslyThreadFor example, set the stack size,ThreadPriority.
 
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 createThread:
[MyObj implements mselectorinbackground: @ selector (myThreadMainMethod) withObject: nil];
The effect is the same as that of detachNewThreadSelector: toTarget: withObject: Of NSThread.
 
 
ThreadSynchronization
ThreadThe synchronization method is similar to that in other systems. We can use atomic operations, mutex, lock, and so on.
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 follows the NSLooking protocol. We can use lock, tryLock, and 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)
{
// Everything between the braces is protected by the @ 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. It differs from mutex in that it is more accurate, waiting for a NSCondtionThreadLocked until otherThreadSent a signal to the condition.
The following is an example:ThreadWait for things to be done, and there is no things to be done by othersThreadIt is notified.
 
 
[CocoaCondition lock];
While (timeToDoWork <= 0)
[CocoaCondition wait];

TimeToDoWork --;
// Do real work here.
[CocoaCondition unlock];
 
OthersThreadTheThreadYou can do the following:
[CocoaCondition lock];
TimeToDoWork ++;
[CocoaCondition signal];
[CocoaCondition unlock];
 
 
ThreadInter-Communication
ThreadDuring runningThreadCommunication. We can use some methods in NSObject:
In the Application masterThreadTo do the following:
PerformSelectorOnMainThread: withObject: waitUntilDone:
Performselecstmmainthread: withObject: waitUntilDone: modes:
 
InThreadTo do the following:
PerformSelector: onThread: withObject: waitUntilDone:
PerformSelector: onThread: withObject: waitUntilDone: modes:
 
In the currentThreadTo do the following:
Optional mselector: withObject: afterDelay:
Optional mselector: withObject: afterDelay: inModes:
 
Cancel sending to currentThreadA message
CancelPreviousPerformRequestsWithTarget:
CancelPreviousPerformRequestsWithTarget: selector: object:
 
For exampleThreadTo notify the masterThreadYou can use the following interface:-(void) myThreadMainMethod
{
NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
// To do something in your thread job
...
[Self defined mselecw.mainthread: @ selector (updateUI) withObject: nil waitUntilDone: 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 events and messages (such as mouse messages, keyboard messages, and timer messages ).ThreadBusy or idle.
The system automaticallyThreadGenerate a corresponding run loop to process its message loop. When you touch UIView, functions such as touchesBegan and touchesMoved are called,
Because the mainThreadIn UIApplicationMain, such a run loop is used to distribute input or timer events.


Multithreading is used in ios development. Commonly Used multithreading classes and methods include # define kBgQueue dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) // 1

Dispatch_async (kSystemAppUpdateQueue, ^ {

NSError * error;

NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: strURL]

Options: 0

Error: & error];

If (error! = Nil ){

NSLog (@ "% @", error. description );

[Self defined mselec1_mainthread: selectorError withObject: nil waitUntilDone: YES];

}

Else {

If (data! = Nil)

{

[Self defined mselecw.mainthread: selectorDone withObject: data waitUntilDone: YES];

}

Else

{

[Self defined mselec1_mainthread: selectorError withObject: nil waitUntilDone: YES];

}

}

});

Return;
One iOS development, multi-thread, and runloop learning Demo !!!!!!!!!!!

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.