[Cocoa] multi-thread nsthread of cocoa

Source: Internet
Author: User
Introduction to cocoa multi-thread nsthread

Luo chaohui (http://www.cnblogs.com/kesalin)

This article follows the "signature-non-commercial use-consistency" creation public agreement

IOS supports multiple levels of multi-threaded programming. The higher the level, the higher the abstraction level, and the more convenient it is to use. It is also Apple's most recommended method. 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:

Thread is relatively lightweight among the three paradigms, but it is also the most responsible for use. You need to manage the thread lifecycle and synchronize threads by yourself. Threads share the same applicationProgramAnd have the same access permissions to the 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 iOS, we can use multiple forms of thread:

Cocoa threads: Use nsthread or use the nsobject class method javasmselectorinbackground: withobject: to create a thread. If you choose thread to implement multithreading, nsthread is the recommended method.
POSIX Threads: a multi-threaded Library Based on the 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 and nsblockoperation.

Grand Central Dispatch (GCD): 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.

Thread creation and startup

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 one will immediately create a thread to do things; the other one will init even if you alloc, however, the thread will not be created until we manually call start to start the thread. This delay implementation idea is useful in many resource-related aspects. In the latter way, We can configure the thread before starting the thread, such as setting the stack size and thread priority.

There is also an indirect method, which is more convenient. We don't even need to explicitly write nsthread-relatedCode. The nsobject class method is used to create a thread:

[Myobj implements mselectorinbackground: @ 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, 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. The difference between it and mutex is that it is more accurate. Wait until a nscondtion thread is locked until other threads send a signal to that 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 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 busy or Idle threads 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 a uiview is touched, the function such as touchesbegan/touchesmoved can be called because the main thread of the application has such a run loop in the uiapplicationmain to distribute input or timer events.

References:

Overview and principles of nsunloop: http://xubenyang.me/384

official documentation: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/

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.