Cat learn iOS (49) thread creation Nsthreand for multithreaded networks

Source: Internet
Author: User

Cat Share, must boutique

Original articles, welcome reprint. Reprint Please specify: Sanayu's Blog
Address: http://blog.csdn.net/u013357243?viewmode=contents

One: basic use of Nsthread 1: Creating and starting Threads

A Nsthread object represents a thread

Creating, starting Threads

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(sel) object:nil];[thread start];

When a thread is started, the run method of self is executed in threads thread

Main thread related usage
+ (Nsthread *) Mainthread; Get the main thread
-(BOOL) Ismainthread; is the main thread
+ (BOOL) Ismainthread; is the main thread

2: Common Other methods

Get current thread

NSThread *current = [NSThread currentThread];

Scheduling Priority for Threads

+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;- (double)threadPriority;- (BOOL)setThreadPriority:(double)p;

The scheduling priority value range is 0.0 ~ 1.0, the default 0.5, the higher the value, the higher the priority

The name of the thread

- (void)setName:(NSString *)n;- (NSString *)name;
3: Other ways to create threads

Automatically start a thread after creating a thread
[Nsthread detachnewthreadselector: @selector (Run) totarget:self Withobject:nil];

Implicitly creating and starting a thread
[Self Performselectorinbackground: @selector (Run) Withobject:nil];

Pros and cons of the above 2 ways to create threads
Advantages: Simple and fast
Cons: Unable to set the thread in more detail

Second: The state of the thread

When we create a thread, his life cycle is:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];

Creation of Threads:

Thread-Open:


Running and blocking of threads:
(1) Set thread Block 1, block 2 seconds

[NSThread sleepForTimeInterval:2.0];

(2) The second set of thread Block 2, the current time as a benchmark to block 4 seconds

NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];[NSThread sleepUntilDate:date];

Performance in memory when a thread handles a blocking state: (Threads are moved out of the scheduler thread pool, not scheduled at this time)

Thread of death:

When a thread's task ends, an exception occurs, or a forced exit of these three cases causes the thread to die.

After the thread dies, the thread object is removed from memory.

Controlling Thread State

Start thread

- (void// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态

Blocking (pausing) threads

+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 进入阻塞状态

Force Stop Thread

+ (void)exit;// 进入死亡状态

Note: Once the thread has stopped (dead), it cannot be opened again.

Three: Multithreading security vulnerability 1: resource sharing

A resource may be shared by multiple threads, that is, multiple threads may access the same piece of resources
For example, multiple threads access the same object, the same variable, the same file

When multiple threads access the same piece of resources, data confusion and data security problems can easily arise.

such as bank access issues:

Question of selling tickets:

Analysis:

Locking

Here is a mutex (synchronous lock) on it, learn Java should understand the concept of lock. I don't have much to explain, it's a bunch of blogs.

Mutex use format
@synchronized (Lock Object) {//code to be locked}
Note: Locking 1 parts of code with only 1 locks, with multiple locks is not valid

Advantages and disadvantages of mutual exclusion lock
Advantages: It can effectively prevent the data security problem caused by multi-thread snatch resource
Cons: Consumes a lot of CPU resources

Use of mutexes: Multiple threads rob the same piece of resources

Related Professional terminology: Thread synchronization
Thread synchronization means that multiple threads are executing on the same line (performing tasks sequentially)
Mutex is the use of thread synchronization technology

IV: Atomic and non-atomic properties Nonatomic and Atomic

1:oc There are two choices for nonatomic and atomic when defining attributes
Atomic: Atomic attribute, locking for setter method (default is Atomic).
Nonatomic: Non-atomic attribute, does not lock the setter method.

Comparison of 2:nonatomic and atomic
Atomic: Thread safety requires a lot of resource consumption.
Nonatomic: Non-thread-safe, suitable for small memory mobile devices.

Recommendations for 3:ios Development
All properties are declared as nonatomic.
Try to avoid multiple threads robbing the same piece of resources.
As far as possible, locking, resource-grabbing business logic to the server-side processing, reduce the pressure of mobile clients.

In a word, we all use nonatomic.

V: Inter-thread communication what is called inter-thread communication

In 1 processes, threads often do not exist in isolation and require frequent communication between multiple threads

1: The embodiment of inter-thread communication
One thread passes data to another thread.
After performing a specific task in one thread, go to another thread to continue the task.

2: Common methods for inter-thread communication

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

PS: The concept of the East cat really lazy to write, may be related to the cat is not a study, the theory and concept is very important, but the air is really not good understanding, combined with practice can be well understood, if some concepts you do not understand, Google or Baidu also white, CSDN blog and so many resources to answer, If the understanding is looming, knock on the code.

Cat learn iOS (49) thread creation Nsthreand for multithreaded networks

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.