A glimpse into the thread of iOS development (100)

Source: Internet
Author: User
1 Preface

This chapter introduces Apple's new method to simplify multithreading and become Grand Central Dispatch (GCD for short). It provides a new set of APIs that can be appliedProgramThe work to be executed is split into smaller blocks that can be distributed across multiple threads and CPUs, thus solving the user experience problem.

2. Details 2.1 simulate easy-to-use operations

Next, let's simulate this time-consuming operation to create a project. When you click Start working, it will wait 10 seconds and then display the content, and output the time-consuming data in the console:

CodeInstance

Zyviewcontroller. m

 

/// Zyviewcontroller. M // slowworker /// created by zhangyuc on 13-6-7. // copyright (c) 2013 zhangyuc. all rights reserved. // # import "zyviewcontroller. H "@ interface zyviewcontroller () @ end @ implementation zyviewcontroller @ synthesize startbutton, resultstextview;-(nsstring *) Wait {// set the thread to sleep for 1 second [nsthread sleepfortimeinterval: 1]; return @ "Hi There";}-(nsstring *) processdata :( nsstring *) Data {[nsthread sleepfortimeinterval: 2]; // converts the return [data uppercasestring];} -(nsstring *) caculatefirstresult :( nsstring *) Data {[nsthread sleepfortimeinterval: 3]; // get the length return [nsstring stringwithformat: @ "Number of chars: % d ", [Data Length];}-(nsstring *) caculatesenondresult :( nsstring *) Data {[nsthread sleepfortimeinterval: 4]; // Replace "E" with "E" return [data stringbyreplacingoccurrencesofstring: @ "E" withstring: @ "E"];}-(void) viewdidload {[Super viewdidload]; // do any additional setup after loading the view, typically from a nib .} -(void) didreceivememorywarning {[Super didreceivemorywarning]; // dispose of any resources that can be recreated .} -(void) dealloc {[startbutton release]; [resultstextview release]; [Super dealloc];}-(ibaction) doworking :( ID) sender {// obtain the current time nsdate * starttime = [nsdate date]; nsstring * fetcheddata = [self fechsomethingfromserver]; nsstring * processeddata = [self processdata: fetcheddata]; nsstring * firstresult = [self caculatefirstresult: processeddata]; nsstring * secondresult = [self outcome: processeddata]; nsstring * resultssummary = [nsstring stringwithformat: @ "first: [% @] \ nsecond: [% @] ", firstresult, secondresult]; // assign resultstextview to the text attribute of resultstextview. TEXT = resultssummary; nsdate * endtime = [nsdate date]; // obtain the time difference unit (s nslog (@ "completed in % F seconds", [endtime timeintervalsincedate: starttime]);} @ end

 

Running result:

Initialization:


After you click Start working, wait for about 10 seconds:


Console running result:

 

11:18:08. 360 slowworker [868: c07] completed in 10.005586 seconds


2.2 Basic thread knowledge

Most modern operating systems support the concept of threads. Each process can contain multiple threads, all of which are performed simultaneously. All threads in a process share executable program code and the same global data. Each thread can also have some unique data. A thread can use a special structure called mutex or lock. This structure ensures that a specific code block cannot be run by multiple threads at a time. This helps ensure correct results.

When processing the thread again, the common problem is thread security. For example, in cocoa touch, the foundation framework is generally considered thread-safe, while the uikit framework is considered unsafe to a large extent. In the IOS application, all method calls for processing any uikit object should be executed from the system thread, which is usually the main thread. By default, the main thread executes all operations of the IOS application (for example, Operations triggered by users ).

2.3 unit of work

The solution recommended by Apple for multi-threaded operations: Split long-running tasks into multiple work units and add these units to the execution queue. The system manages these queues for us and executes work units on multiple threads. We do not need to directly start and manage backend threads. We can get rid of too many "Registration" tasks involved in implementing concurrent applications. The system will do these tasks for us.



In the next section, we will introduce how Apple uses multithreading.

3 conclusion

All of the above content is expected to help you.

Demo: http://download.csdn.net/detail/u010013695/5537663

 

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.