IOS multithreaded nsthread nsoperation nsoperationqueue GCD line lock thread blocking

Source: Internet
Author: User
Tags gcd

The application of the thread in the iphone is not uncontrolled, the official data shows that the main thread of the iphone OS stack size is 1M, the second thread is 512KB, and the value cannot be changed by the compiler switch or thread API function, only the main thread has the ability to directly modify the UI, So some data planes can open up threads to operate, and the iOS threading method has nsthread nsoperation nsoperationqueue GCD:

The Nsthread method has

//Nsthread Automatic-(Ibaction) Didclicknsthreadautobuttonaction: (ID) Sender {//Create a child thread, which is a child thread//Selector runs the method in a child thread, Target executes the method object on the child thread, and object is the method parameter[Nsthread detachnewthreadselector: @selector (cycle) totarget:self Withobject:nil]; }//nsthread Manual-(Ibaction) Didclicknsthreadhandbuttonaction: (ID) Sender {Nsthread*thread = [[Nsthread alloc]initwithtarget:self selector: @selector (cycle)Object: nil]; [Thread start];//manually turn on threads        }

Create threads directly with NSObject's class method

// nsoperation Invocation Method Creation thread -(ibaction) Didclickinvocationbuttonaction: (ID) sender {         // Operations Object, encapsulation method implementation and data    object: nil];        [Operation start]; // start execution of stored methods in operation     }

Using the Nsoperation method

//Nsoperation Invocation method to create a thread-(Ibaction) Didclickinvocationbuttonaction: (ID) Sender {//manipulating objects, encapsulating method implementations, and dataNsinvocationoperation *operation = [[nsinvocationoperation alloc]initwithtarget:self selector: @selector (cycle)Object: nil]; [Operation start];//start execution of stored methods in operation    }//Nsoperation Block Method-(Ibaction) Didclickblockbuttonaction: (ID) Sender {nsblockoperation*operation = [Nsblockoperation blockoperationwithblock:^{                //encapsulate the method to be executed         for(inti =0; I <Ten; i++) {NSLog (@"current thread = =%@ is the main thread = =%d I:%d", [Nsthread currentthread],[nsthread ismainthread],i);        }            }]; //Execution Method[Operation start]; }

Using Nsoperationqueue thread queuing

//nsoperationqueue Creating thread Queues-(Ibaction) Didclickoperationqueuebuttonaction: (ID) Sender {//thread differentiation: out-of-thread and non-detached threads//out-of-thread: When a feature in a thread is implemented, the thread is shut down and destroyed. Nsthread the thread created by the NSObject method. Default is out of thread//non-detached threads: After a feature in a thread is implemented, the thread goes to sleep and waits for it to be used again. The Runloop in the detach thread runs and is not closed, which becomes a non-detached thread.        The thread created by Nsoperationqueue is a non-detached thread. //The action queue implements concurrent execution of multiple threads. //thread synchronization: After the current thread finishes executing, the next thread starts executing. //How to implement thread synchronization: Set the maximum number of concurrent operations queues to 1; //Create thread QueueNsoperationqueue *queue =[[Nsoperationqueue alloc]init]; //set the operation queue at the same time maximum number of threads concurrentlyQueue.maxconcurrentoperationcount =5;  for(inti =0; I <Ten; i++) {nsinvocationoperation*operation = [[nsinvocationoperation alloc]initwithtarget:self selector: @selector (cycle)Object: nil]; //add to Thread queue[Queue addoperation:operation];    [Operation release]; }        }

Travel queues using the GCD method

//gcd serial Queue-(Ibaction) Didclickserialbuttonaction: (ID) Sender {//There are two types of serial queues//mainqueue Home column, GCD created and supplied, is a serial queue by default in the primary queue, and executes in code orderdispatch_queue_t Mainqueue =Dispatch_get_main_queue (); //Add a task to the home column, parameter one: queue parameters for administrative tasks two: block that encapsulates the task codeDispatch_async (Mainqueue,^{NSLog (@"the first task ===%@ the thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Mainqueue,^{NSLog (@"The second task ===%@ the thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);          }); Dispatch_async (Mainqueue,^{NSLog (@"the third task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Mainqueue,^{NSLog (@"Fourth Task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Mainqueue,^{NSLog (@"Fifth Task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);        }); //in defining a queue, you need to create it yourself and set it to a serial dispatch_queue_serial serial interface//dispatch_queue_t queue = dispatch_queue_create ("Myqueue", dispatch_queue_serial);//    //dispatch_async (queue, ^{//NSLog (@ "First task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "second task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Third task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Fourth task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Fifth task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });    }

Using GCD parallel queues

//gcd Parallel Queue-(Ibaction) Didclickconcurrentbuttonaction: (ID) Sender {//There are two types of parallel queues//Global queue, CGD create//dispatch_queue_t queue = dispatch_get_global_queue (Dispatch_queue_priority_default, 0);//    //dispatch_async (queue, ^{//NSLog (@ "First task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "second task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Third task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Fourth task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    });//dispatch_async (queue, ^{//NSLog (@ "Fifth task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);//    }); //Custom queue, you need to create it yourself, and set up parallel queue Dispatch_queue_concurrent parallel interfacedispatch_queue_t Queue= Dispatch_queue_create ("Concurrent Queue", dispatch_queue_concurrent); //Add a taskDispatch_async (Queue, ^{NSLog (@"the first task ===%@ the thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Queue,^{NSLog (@"The second task ===%@ the thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Queue,^{NSLog (@"the third task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Queue,^{NSLog (@"Fourth Task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);    }); Dispatch_async (Queue,^{NSLog (@"Fifth Task ===%@ thread ===%d", [Nsthread currentthread],[nsthread ismainthread]);        }); }

Use GCD to download pictures for real action

//actual download picture Operation-(Ibaction) Didclickgcdownloadbuttonaction: (ID) Sender {dispatch_queue_t queue= Dispatch_get_global_queue (Dispatch_queue_priority_default,0); //The task is added to the global queue and can be dispatched to the child thread to executedispatch_async (Queue,^{                //This is in the child threadNSString*imageurl =@"http://a.hiphotos.baidu.com/image/pic/item/96dda144ad3459824a56a41a0ef431adcaef845e.jpg"; NSData*data =[NSData Datawithcontentsofurl:[nsurl Urlwithstring:imageurl]; UIImage*image =[UIImage Imagewithdata:data]; NSLog (@"image =%@", image); NSLog (@"Task ===%@ Thread ===%d", [Nsthread currentthread],[nsthread ismainthread]); //displaying images on the main thread//Add a task to the main queue, the home row distributes the task to the main threadDispatch_async (Dispatch_get_main_queue (),^{                        //now it's the main thread.NSLog (@"Task ===%@ Thread ===%d", [Nsthread currentthread],[nsthread ismainthread]); _imageview.image=image;            });    }); }

The first of the thread blocking methods:

[Nsthread sleepforinterval:2.0]//consciousness is that the thread waits 2 seconds to run

The second set of threading blocking NSDate *date=[nsdate datewithtimeintervalsincenow:4.0]; [Nsthead Sleepuntildate:date]; Thread Lock classic case selling train tickets
_lock = [[Nslock alloc]init]; // creating mutexes, multiple threads sharing using
//Sell train Tickets- (void) Saletickets: (dispatch_queue_t) queue{ while(_surpluscount >0) {[_lockLock];//Get Mutex lock//sleep 0.1 seconds per execution[Nsthread Sleepfortimeinterval:0.1]; Const Char*queuelabel =Dispatch_queue_get_label (queue); NSString*label =[NSString Stringwithutf8string:queuelabel]; NSLog (@"current train ticket sold by%@:%d tickets", Label,_surpluscount); _surpluscount--; [_lock unlock];//Unlock            }    }

.........

IOS multithreaded nsthread nsoperation nsoperationqueue GCD line lock thread blocking

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.