iOS Multi-Threading

Source: Internet
Author: User
Tags gcd

One, multi-threaded 1, what is multi-threaded

Nsthread

(1) Multithreading can handle requests for multiple tasks at the same time. If you want to perform multiple tasks at the same time, you need to open a new thread. The execution of the program is executed serially, if multiple tasks are executed in parallel.

  // Create a new thread 1    Object : nil];    [Thread1 start];     // Create a new thread 2    [Nsthread detachnewthreadselector: @selector (taskb:) totarget:self Withobject:nil];

(2) What problems can be solved by multithreading?

//

Essentially, it is mainly to solve the problem of the interface card that occurs when a time-consuming task executes, so that multiple tasks can be executed simultaneously, such as thunder download.

//

Scenes using, such as barley nets, some pictures download time 5 seconds, or load 1G files, need to start multithreading.

//

(3) thread synchronization and lock presentation issues

The CPU takes the data change value out of memory and then puts it back into memory, which may be incorrect if multithreaded access. The solution is locking.

-(void) add{ for(intI=0; i< +; i++) {[_lockLock]; _num++; NSLog (@"Add ==%d", _num);    [_lock unlock]; }}-(void) sub{ for(intI=0; i< +; i++) {[_lockLock]; _num--; NSLog (@"Sub ==%d", _num);    [_lock unlock]; }}

Project development, noatomic when a property only UI interface Access can be added, improve access speed. If this property is created by a child thread, do not add noatomic to secure the thread.

The UI thread is called the main thread, and the other threads that are created are called working sub-threads

Note: Do not manipulate the UI directly in child threads

{ .......
///How the child threads update the UI (important) to avoid problems with the code. Eg: Download progress update///The UI thread is called the main thread, and the other threads that are created are called working sub-threads, note: Do not manipulate the UI directly in a child thread (to make the main thread manipulate the UI indirectly)_progressview =[[uiprogressview Alloc] Initwithframe:cgrectmake ( -, $, -,Ten)]; [Self.view Addsubview:_progressview]; [Nsthread detachnewthreadselector: @selector (downloadnetworkingdata) totarget:self Withobject:nil]; }#pragmaMark--Demo Download Data-(void) downloadnetworkingdata{//analog 10s Network download for(intI=0; i< -; i++) { //_progressview.progress +=0.01; Do not operate the UI interface here//The following statement is the process of indirectly manipulating the UI[Self performselectoronmainthread: @selector (UpdateUI) Withobject:nil Waituntildone:yes]; [Nsthread sleepfortimeinterval:0.1]; }}-(void) updateui{_progressview.progress+=0.01;}

Second, nsopetation

1. What is Nsoperation

is also a mechanism to implement multithreading, in Nsthread do a higher abstraction, joined the block, more than nsthread easy to use

Third, GCD

1. Grand Central Dispatch Shorthand

Advantages: Support multi-core, C and block interface, easy to use, powerful.

1. Create an asynchronous task [self creatasynctask];2. analog network download [self simulatenewokingdownload];3. Just execute once [self runOnce]; 4。 Delay execution [self delayrun]; 5Notifications perform multiple tasks, waiting for all tasks to be processed when execution is complete [self grouprun]; ===============-(void) grouprun{//group Task Group dispatch_group_t Group =Dispatch_group_create (); Add task, 7 seconds to complete Dispatch_group_async (group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{//for (int i=0; i<100; i++) {NSLog (@ "a=%d"), i); [Nsthread sleepfortimeinterval:0.07]; } }); Add task, 5 Seconds to complete Dispatch_group_async (group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{//for (int i=0; i<100; i++) {NSLog (@ "b=%d"), i); [Nsthread sleepfortimeinterval:0.05]; } }); Add task, 10 seconds to complete Dispatch_group_async (group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{//for (int i=0; i<100; i++) {NSLog (@ "c=%d"), i); [Nsthread sleepfortimeinterval:0.1]; }});//monitoring completed Operation Dispatch_group_notify (group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{NSLog (@ "All Tasks completed"); });} -(void) delayrun{//5s after output dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (5*nsec_per_sec)), Dispatch_get_main_ Queue (), ^{//NSLog (@ "haha")); });} -(void) runonce{Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{NSLog (@ "Execute code only once");});} -(void) simulatenewokingdownload{_progressview =[[uiprogressview alloc] Initwithframe:cgrectmake (50, 200, 250, 10)]; [Self.view Addsubview:_progressview]; Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^ {for (int i=0; i<10; i++ ) {////Last Show Dialog  Dispatch_async (Dispatch_get_main_queue (), ^  {_progre Ssview.progress +=0.1 ;}); [Nsthread sleepfortimeinterval:1 ];} Dispatch_async (Dispatch_get_main_queue (), ^  {uialertview *alertview =  [[Uialertview alloc] init]; Alertview.message [email protected] "Download Done" ; [Alertview addbuttonwithtitle:@ "Cancel" ]; [Alertview show]; }); });} #pragma mark--gcd test Method-(void ) creatasynctask{//Create an asynchronous task, parameter 1, incoming queue, 3 Queue:main Queue Home column, global queue A worker thread; custom Queue dispatch_queue_t queue=dispatch_get_global_queue (dispatch_queue_priority_default, 0 ); dispatch _async (Queue, ^  {for (int i=0; i<20; i++ ) {NSLog (@ "a===%d" , I);}}); Dispatch_async (queue, ^  { for (int i=0; i<20; i++ ) {NSLog (@ "b===%d" , I);}});        

iOS Multi-Threading

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.