Multi-Threading Focus summary for iOS development

Source: Internet
Author: User

1. Asynchronous concurrent queue: it is used more


- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{ //Dispatch_sync: Synchronous, without the ability to open threads//Dispatch_async: Asynchronous, with the ability to open threads//concurrent queues: Multiple tasks can be executed concurrently//serial queue: Once a task is finished, the next task is executed//get a global concurrent queuedispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0); //Add a task to the global queue to execute asynchronouslyDispatch_async (Queue, ^{NSLog (@"-----Download Image 1---%@", [Nsthread CurrentThread]); }); Dispatch_async (Queue,^{NSLog (@"-----Download Image 2---%@", [Nsthread CurrentThread]); }); Dispatch_async (Queue,^{NSLog (@"-----Download Image 3---%@", [Nsthread CurrentThread]); }); Dispatch_async (Queue,^{NSLog (@"-----Download Image 4---%@", [Nsthread CurrentThread]); }); Dispatch_async (Queue,^{NSLog (@"-----Download Image 5---%@", [Nsthread CurrentThread]); });}

2. Download the image asynchronously and then go back to the main line loads load image Refresh UI

- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Queue Addoperationwithblock:^{        //1. Download images asynchronouslyNsurl *url = [Nsurl urlwithstring:@"http://d.hiphotos.baidu.com/image/pic/item/37d3d539b6003af3290eaf5d362ac65c1038b652.jpg"]; NSData*data =[NSData Datawithcontentsofurl:url]; UIImage*image =[UIImage Imagewithdata:data]; //2. Back to the main thread, display the picture//[Self performselectoronmainthread:<# (SEL) #> withobject:<# (ID) #> waituntildone:<# (BOOL) #>];< /c8>//Dispatch_async (Dispatch_get_main_queue (), ^{//            //        });[[Nsoperationqueue Mainqueue] addoperationwithblock:^{self.imageView.image=image;    }]; }];}

3. Adding dependencies between thread tasks

- (void) dependency{/** Assume A, B, c three operations, requirements: 1.3 operations are executed asynchronously 2. Operation C relies on Operation B 3. Operation B depends on operation a*/        //1. Create a queue (not a home row)Nsoperationqueue *queue =[[Nsoperationqueue alloc] init]; //2. Create 3 ActionsNsblockoperation *operationa = [Nsblockoperation blockoperationwithblock:^{NSLog (@"A1---%@", [Nsthread CurrentThread]);        }]; Nsblockoperation*OPERATIONB = [Nsblockoperation blockoperationwithblock:^{NSLog (@"B---%@", [Nsthread CurrentThread]);    }]; Nsblockoperation*operationc = [Nsblockoperation blockoperationwithblock:^{NSLog (@"C---%@", [Nsthread CurrentThread]);        }]; //Setting Dependencies[Operationb Adddependency:operationa];        [Operationc ADDDEPENDENCY:OPERATIONB]; //3. Add operations to the queue (automatically execute tasks asynchronously)[Queue Addoperation:operationc];    [Queue Addoperation:operationa]; [Queue addoperation:operationb];}

4. Maximum number of concurrent

Queue. Maxconcurrentoperationcount = 3;

5. Thread operations are generally canceled in memory warnings

[Queue cancelalloperations];//non-recoverable operation

[Queue Setsuspended:yes]; Pause All tasks in a queue

  [Queue Setsuspended:no]; Recover All tasks in a queue

6. Thread safety: Need to lock @synchronize (self) {}

Create multiple threads First: Perform the same task (you need to assign an initial value to the ticket number to achieve the ticket sale)

-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *)event  {        [ Nsthread detachnewthreadselector: @selector (sellticket:) totarget:self withobject:@ "a" ];    [Nsthread detachnewthreadselector: @selector (sellticket:) totarget:self withobject:@ "b " ];    [Nsthread detachnewthreadselector: @selector (sellticket:) totarget:self withobject:@ "C " ];        }

Then lock the task implementation:

//the way to buy tickets requires encryption- (void) Sellticket: (NSString *) name { while(1) {@synchronized (self) {if(Self.ticketcount >0) {[Nsthread sleepfortimeinterval:0.3]; Self.ticketcount--; NSLog (@"%@---%d----%@---%d", [Nsthread currentthread],[nsthread Ismainthread],name,self.ticketcount); } Else {                return; }        }    }    }












Multi-Threading Focus summary for iOS development

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.