IOS multi-thread learning notes (GCD, RunLoop, NSThread), runloopnsthread

Source: Internet
Author: User

IOS multi-thread learning notes (GCD, RunLoop, NSThread), runloopnsthread

// Obtain the main thread:

[NSThread mainThread];

{Number = 1, name = main}

// Obtain the current thread:

[NSThread currentThread];

// Determine whether the main thread is used:

[NSThread ismainThread]; (BOOL)

Or

[[NSThread currentThread] ismainThread]; (BOOL)

// Use pThread: (C implementation, cross-platform, header file # include )

Pthread_t thread;

Pthread_create (& thread, attributeOfThread, func, funcPara );

// NSThread usage:

NSThread * thread = [[NSThread alloc] initWithTraget: self selector: @ seletor (run :) object: runPara];

[Thread start];

(Create a new thread and run the thread to automatically destroy it after execution is completed)

Or

[NSThread detachNewThreadSeletor: @ seletor (run :) toTarget: self withObject: runPara];

(Ion separation thread)

Or

[Self defined mseletorinbackgroud: @ seletor (run :) withObject: runPara];

(Enable background threads)

Blocked thread:

[NSThread sleepForTimeInterval :( float)];

[NSThread sleepUntilDate: [NSDate dateWithIntervalSinceNow: 3.0];

Launch thread: (destroy thread ?)

[NSThread exit];

// Atomic and non-atomic attributes:

Atomic: locks the setter method;

Nonatomic: the setter is not locked;

// Inter-thread communication:

-(Void) specified mselecw.mainthread :( SEL) aSeletor withObject :( id) arg waitUntilDone :( BOOL) wait;

-(Void) implements mseletor :( SEL) aSeletor onThread :( NSThread *) the withObject :( id) arg waitUntilDone :( BOOL) wait;

// GCD basic usage: (all functions start with dispatch _ and use the C language)

// Create a queue:

Dispatch_queue_t queue = dispatch_queue_create (char * label, macro );

The macro values include (queue type ):

DISPATCH_QUEUE_CONCURRENT (concurrency)

DISPATCH_QUEUE_SERIAL (Serial)

// Encapsulate the asynchronous task block to the concurrent queue:

Dispatch_async (queue, block); (concurrent queue)

Starts a new thread and runs it asynchronously.

// Encapsulate the asynchronous task block to the serial queue:

Dispatch_sync (queue, block); (Serial queue)

The thread is also enabled, but only one thread is enabled for serial execution.

// Encapsulate the synchronization task block to the concurrent queue:

// Encapsulate the synchronization task block to the serial queue:

Dispatch_async (queue, block); (concurrent queue)

Dispatch_sync (queue, block); (Serial queue)

The thread is not enabled and is executed serially in the main thread.

// In addition, encapsulate the task by calling a function (not a block:

Dispatch_async (queue, context, Cfunc );

// Global concurrent queue: (obtain an existing Queue)

Dispatch_get_global_queue (priority, which is 0 by default for future use );

The priority is DISPATCH_QUEUE_PRIORITY_BACKGROUND.

DISPATCH_QUEUE_PRIORITY_DEFAULT

DISPATCH_QUEUE_PRIORITY_LOW

DISPATCH_QUEUE_PRIORITY_HIGH

(Descending order of priority)

// Main queue: all tasks in the main queue will be executed in the main thread!

// Create:

Dispatch_queue_t queue = dispatch_get_main_queue ();

?? Note: Do not add the synchronization function to the main queue in the main thread. A deadlock will occur!

?? Summary:

(1) Concurrent queues can only be used for asynchronous tasks, while serial queues can be used for asynchronous or synchronous tasks.

(2) The synchronous function blocks the current thread and the asynchronous function does not block the current thread.

(3) If the synchronization function in the main thread blocks the main thread, a new thread cannot be created, but a new queue needs to be executed, therefore, the main thread is used for serial execution. If this task is added to the main queue, a deadlock occurs. If it is not in the main thread, the synchronization function will only block the current thread, because the main thread is still idle, you can schedule the main thread to execute these tasks.

// GCD thread communication:

When you want to return to the main thread after creating a thread, place the code you want to execute in the main thread into the main queue through nesting!

// Advantages of delayed execution and GCD latency:

1. [self defined mseletor: @ seletor (task) withObject: nil afterDelay: seconds];

2. [NSTimer scheduledTimerWithTimeInterval: seconds target: self selector: @ selector (task) userInfo: nil repeats: whether repeated];

3. dispatch_after (dispatch_time {related time information}, queue to be placed, ^ {code to be executed });

When GCD is advantageous, you can determine the thread in which the code in the block will be executed after the delay

// GCD implements one-time code:

This one-time method means that the code is executed only once during the entire program running, while lazy loading means that the code is loaded only once for an object.

// IOS RunLoop:

// There are two frameworks in iOS: nsunloop (OC, bottom layer: CFRunLoopRef) and CFRunLoopRef (C)

// The running mode of CFRunLoop is CFRunLoopModeRef. The mode includes source, timer, and observer.

Mode: (the first two are more common)

1) kCFRunLoopDefaultMode: the default mode. The main thread runs in this mode by default.

2) UITrackingRunLoopMode

3) UIInitializationRunLoopMode: the mode when the App is started. It is no longer used after the App is started.

4) GSEventReceiveRunLoopMode: receives the internal mode of the system event, which is usually unavailable.

5) kCFRunLoopCommonMode: placeholder mode (This prevents the event from being affected by mode switching!)

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.