iOS development-multithreaded programming technology (thread, COCOA operations, GCD)

Source: Internet
Author: User
Tags gcd

In software development, multithreaded programming technology is widely used, I believe that the multi-threaded task is no longer unfamiliar to us. With multithreading, we can do multiple things, rather than one task at a to do. For example: front-end and background for interaction, large tasks (need to spend a certain amount of time and resources) and so on. That is, we can use threads to put long-occupied tasks into the background, without affecting the user's use.

Definition of Thread:

Each program that is running on the system is a process. Each process contains one or more threads. A process can also be a dynamic execution of an entire program or part of a program. A thread is a set of instructions, or a special section of a program that can be executed independently in a program. It can also be understood as the context in which the code runs. So a thread is basically a lightweight process that is responsible for multitasking in a single program. Typically, the operating system is responsible for scheduling and executing multiple threads.

Turn from Baidu Encyclopedia: Multithreading

multithreaded technologies supported by iOS:

First, Thread:

1) Create thread explicitly: nsthreed

2) implicitly created thread: NSObject

Second, COCOA operations:

The Nsoperation class is an abstract class, because we must use its two subclasses.

  1) nsinvocationoperation

2) nsblockoperation

————————————————————————————

3) Nsoperationqueue (inherited from NSObject)

Iii. Grand Central Dispatch (GCD):

1) Creation of GCD

2) Recurring thread: dispatch_apply

3) Operation queue: Dispatch_queue_create

4) GCD Group notification: dispatch_group_t

5) GCD Implementation Timer

First, Thread

We can use the Nstherad or NSObject class to invoke:

1) Create thread explicitly: Nsthread

There are two ways to create Nsthread

1.1) You need to use the Start method after creation to execute the method:

Object : nil]; [Threadalloc start];

1.2) Create and execute the method immediately:

[Nsthread detachnewthreadselector: @selector (threadalloc:) totarget:self Withobject:nil];

2) implicitly created thread: NSObject

We can also call methods directly using the NSObject class method

[Self Performselectorinbackground: @selector (Threadalloc) Withobject:nil];

Nsthread related properties and methods:

//gets/sets the name of the thread@property (copy) NSString*name Ns_available (10_5, 2_0);/** * Gets the thread object of the current thread * * Through this property, you can see the current thread is the first thread, the main path is 1. * You can see the current thread's ordinal number and name, the main thread sequence number is 1, superimposed in turn. */+ (Nsthread *) CurrentThread;//thread hibernation (seconds)+ (void) Sleepfortimeinterval: (Nstimeinterval) ti;//thread hibernation, specifying exactly what time to hibernate+ (void) Sleepuntildate: (NSDate *) Date;//Exit Thread//Note: This will destroy the thread object! The thread cannot be started again after it is destroyed, or the program crashes. + (void) exit;

Second,Cocoa operations

1) nsinvocationoperation

//Create a thread taskNsoperationqueue *queue =[[Nsoperationqueue alloc] init];//Thread ANsinvocationoperation *operation =[[Nsinvocationoperation alloc] Initwithtarget:self Selector: @selector (operation1)Object: nil];//thread BNsinvocationoperation *operation2 =[[Nsinvocationoperation alloc] Initwithtarget:self Selector: @selector (operation2)Object: nil];//Add a thread A/b to the queue[Queue addoperations:@[operation, Operation2] waituntilfinished:yes];

You must use the Addoperations: method to add a thread to the queue, or the thread will not execute. Alternatively, you can use the Addoperation: method to add a single thread.

2) nsblockoperation

For a simple introduction to use the example, have written a note, it is no longer explained:

//Create a thread taskNsblockoperation *blockoperation =[nsblockoperation blockoperationwithblock:^{NSLog (@"One -%@", [Nsthread CurrentThread]); }];;//Add a new action[Blockoperation addexecutionblock:^{NSLog (@"Double-%@", [Nsthread CurrentThread]);}];//Add a new action[Blockoperation addexecutionblock:^{NSLog (@"three-%@", [Nsthread CurrentThread]);}];//Perform thread Tasks[Blockoperation start];

3) Nsoperationqueue

Here's a look at nsoperation dependencies that affect the order in which threads are executed:

//Create an action queueNsoperationqueue *queue =[[Nsoperationqueue alloc] init];//Thread ANsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"OP1"); [Nsthread sleepfortimeinterval:2];}];//thread BNsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"OP2");}];//thread CNsblockoperation *OP3 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"OP3"); [Nsthread sleepfortimeinterval:2];}];//Thread b relies on thread C, that is, when thread C finishes executing, thread B[Op2 adddependency:op3];//thread C relies on thread A, ditto, except that dependent objects are changed to thread a[Op3 ADDDEPENDENCY:OP1];//to add a thread to a queue[Queue Addoperation:op1]; [Queue ADDOPERATION:OP2]; [Queue addoperation:op3];

Note: Dependencies can be multi-dependent, but do not establish circular dependencies.

In the Nsoperationqueue class, we can use the Cancelalloperations method to cancel all threads. It is necessary to explain here that the following queue will not be executed until the Cancelalloperations method is executed, as soon as the current queue is executed.

nsoperation methods and properties:

// set the maximum number of concurrent threads @property Nsinteger maxconcurrentoperationcount; // block called after the thread completes void (^completionblock) (void); // Cancel Thread -(void) cancel;

Just list the above, the other methods are not all listed.

Iii. Grand Central Dispatch (GCD)

1) Creation of GCD:

0), ^{    NSLog (@ " thread-%@", [Nsthread CurrentThread] );

GCD can also create synchronized threads, just change the async to sync.

2) Recurring thread: dispatch_apply

The following code executes 4 times:

Dispatch_apply (4, Dispatch_queue_priority_default, ^(size_t index) {    //  Index is the number of executions 0 start incrementing    NSLog (@ "one-%ld", Index);});

The index parameter is the number of executions, 0 starts incrementing

3) Operation queue: Dispatch_queue_create

//Create a queue//The first parameter is "string ID", the second argument is optional and can be nulldispatch_queue_t queue = Dispatch_queue_create ("Com.garvey.post", NULL);//Pass in a queue and execute the queue (sequential execution)Dispatch_async (Queue, ^{NSLog (@"AAA"); [Nsthread sleepfortimeinterval:2];}); Dispatch_async (Queue,^{NSLog (@"BBB"); [Nsthread sleepfortimeinterval:1];}); Dispatch_async (Queue,^{NSLog (@"CCC");});

Code effect: Above will be executed first aaa-"bbb-" CCC

4) GCD Group notification: dispatch_group_t

GCD advanced usage, and so on when all the threads have finished their work, then notify.

//Create a groupdispatch_group_t Group =dispatch_group_create ();//Thread ADispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{NSLog (@"group1"); [Nsthread sleepfortimeinterval:2];});//thread BDispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{NSLog (@"group2");});//notifications to be called after threads in the group are completedDispatch_group_notify (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{NSLog (@"Group Success");});

After both thread A and thread B have finished executing, the notification printing group success is called.

5) GCD Implementation Timer

__blockintTime = -;d ispatch_queue_t Queue= Dispatch_get_global_queue (Dispatch_queue_priority_default,0);d ispatch_source_t timer= Dispatch_source_create (Dispatch_source_type_timer,0,0, queue);d Ispatch_source_set_timer (timer, Dispatch_time_now,1.0* Nsec_per_sec,0);d Ispatch_source_set_event_handler (timer,^{ Time--; NSLog (@"%d", time); if(Time = =0) {dispatch_source_cancel (timer); }});d Ispatch_resume (timer);

Code effects: A timer is created, the timer runs for 30 seconds, and every second it calls the block, and we can write code in the block. Because dispatch_source_t is suspended by default, we need to use the Dispatch_resume method to recover first, otherwise the thread will not execute.

GCD Methods and properties:

//get the main threadDispatch_get_main_queue ()//Create queue: The first parameter is "string ID", the second argument is optional, can be nulldispatch_queue_t dispatch_queue_create (Const Char*label, dispatch_queue_attr_t attr);//To create an asynchronous dispatch queuevoidDispatch_async (dispatch_queue_t queue, dispatch_block_t block);//Recovery QueuevoidDispatch_resume (dispatch_object_tObject);//Pause QueuevoidDispatch_suspend (dispatch_object_tObject);

Summary: This article mainly describes the iOS three threads of thread usage, three kinds of threads each have the advantage. Apple is recommending us to use GCD, because GCD is the most lightweight of these three kinds, and it consumes the lowest resources, and it performs more efficiently than the other two kinds. However, it is better to look at the individual use and development requirements to define.

Off-topic: This blog post is the longest I have ever published a technical essay, but also consumes the most energy of the essay, like Friends hope to give a praise, thank you.

This article refers to:

iOS multithreaded Development

Another use of GCD is to allow programs to run longer in the background.

Full mastery of iOS multithreading Raiders--ps: This strategy is more, but there are a lot of repetitive content.

Blog Garveycalvin

Blog Source: http://www.cnblogs.com/GarveyCalvin/

This article copyright belongs to the author and the blog Garden altogether, welcome reprint, but must retain this paragraph statement, and gives the original link, thanks cooperation!

iOS development-multithreaded programming technology (thread, COCOA operations, GCD)

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.