Ios--gcd

Source: Internet
Author: User
Tags gcd

GCDThe abbreviation for Grand Central Dispatch. Grand Central Dispatch (GCD) is a relatively new solution for multi-core programming developed by Apple. It is primarily used to optimize applications to support multicore processors as well as other symmetric multi-processing systems. It is a parallel task performed on the basis of a thread pool pattern. For the first time in Mac OS X 10.6 Snow Leopard, it can also be used in iOS 4 and later. Design GCD is an efficient and powerful technique for replacing technologies such as Nsthread. GCD can handle complex asynchronous programming issues such as data locking and resource leaks. GCD works by letting a program schedule them to perform specific tasks in parallel on any available processor core, depending on the available processing resources. This task can be a function or a program segment. GCD still uses threads at a very low level, but it does not require the programmer to pay attention to too much detail. The queue created by GCD is lightweight, and Apple declares that a GCD unit of work needs to consist of 15 instructions. That is to say, creating a traditional thread can easily require hundreds of instructions. A task in GCD can be used to create a work item or event source that is placed in a queue. If a task is assigned to an event source, then a unit of work consisting of a function or block is placed in an appropriate queue. Apple believes that GCD is more efficient than the normal one-by-one execution of tasks. Features This scheduling framework declares several data types and functions to create and manipulate them: one, the dispatch queue for all scheduling queues are FIFO, so the tasks in the queue begin in the same order as they were added to the queue. GCD automatically provides us with some scheduling queues, and we can also create new ones for specific purposes. The following lists the types of scheduling queues available and how to use them. Second, scheduling resources it is an object that monitors certain types of events. When these events occur, it automatically places a block into the execution routine of a dispatch queue. Third, the scheduling group allows multiple tasks to be grouped to facilitate later to join the implementation. A task can be added to a queue as a member of a group, and the client can use the group object to wait until all the tasks in the group are completed. Iv. Dispatch Semaphore allows clients to publish a certain number of tasks in parallel. Before you begin, it is necessary to understand that the code block to be provided to the GCD queue is used to schedule the run on a system or user-created queue. 1. Declare a queue that returns a user-created queue as follows:
1     dispatch_queue_t myQueue = dispatch_queue_create("com.iphonedevblog.post", NULL);
Where the first parameter identifies the queue, the second parameter is the parameter used to define the queue (not currently supported, so pass in null). 2. Execute a queue the incoming code is executed asynchronously as follows:
1     dispatch_async(myQueue, ^{ [self doSomething]; });
Where you first pass in a previously created queue, and then provide a block of code that is run by the queue. 3. Declaring and executing a queue if you do not need to keep a reference to the queue that you want to run, you can implement the previous functionality by using the following code:
123     dispatch_async(dispatch_queue_create ("com.iphonedevblog.post", NULL), ^{     [self doSomething]; } );
pausing a queueIf you need to pause a queue, you can call the following code. Pausing a queue prevents all code associated with that queue from running.
1 dispatch_suspend(myQueue);//恢复一个队列
If you pause a queue, do not forget to recover. Pause and resume operations are similar to retain and release in memory management. Calling Dispatch_suspend increases the pause count, while the dispatch_resume decreases. The queue starts running only if the pause count becomes zero.
1 dispatch_resume(myQueue);
4. Running code from the queue in the main thread some operations cannot run in an asynchronous queue, so they must be run on the main thread (one for each application). The UI drawing and any calls to Nsnotificationcenter must be made on the mainline stroke. An example of accessing the main thread and running code in another queue is as follows:
123 /*dispatch_sync(dispatch_get_main_queue(), ^{         [self dismissLoginWindow]; });*/在主线程中使用会造成死锁,慎用!
Note that dispatch_suspend (and dispatch_resume) do not work on the main thread. The instance can be used in John Siracusa's ArsTechnicaBlog article Snow Leopard review found two examples demonstrating how to use the Grand Central Dispatch. First, a document-processing application has a function called analyzedocument that will do some statistical documentation of the words and paragraphs of the thing. Typically, this will be a fast process, and the delay between the time the user does not notice that a key is pressed and the result is displayed is already executed in the main thread.
123456 -(IBAction)analyzeDocument:(NSButton*)sender{    NSDictionary*stats=[myDoc analyze];    [myModel setDict:stats];    [myStatsViewsetNeedsDisplay:YES];    [stats release];}
If a document is too large and takes a long time to execute, the main thread pauses to wait for the function to complete. If it takes a long time, the user will notice the delay and the application will not even respond. The solution to this problem is as follows:
123456789 -(IBAction)analyzeDocument:(NSButton*)sender{    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{    NSDictionary*stats=[myDoc analyze];    dispatch_async(dispatch_get_main_queue(),^{        [myModel setDict:stats];        [myStatsView setNeedsDisplay:YES];        [stats release];});    });};
Here, the call to [MyDoc Analyze] is first placed in a block and then into a global concurrency queue. After the [MyDoc Analyze] operation is completed, a new block is placed on the home joins (the application main thread runs on it) and the GUI is updated (this is necessary because the GUI can only be updated by the main thread). With these two minor changes, the developer avoids potential pauses that can be seen by the user and allows the application to make better use of the hardware resources. The second example is a parallel for loop:
1234 for(i=0;i<count;i++){    results[i]=do_work(data,i);}total=summarize(results,count);
This code calls the number of Do_work functions, assigns the result of the first I to the first element of the array, and then calls the summarize function after the loop ends. These operations are executed sequentially, and are not actually required. Assuming that the Do_work function does not require the results of other function calls, these calls can be run at the same time. This is the approach in GCD:
1234 dispatch_apply(count,dispatch_get_global_queue(0,0),^(size_ti){    results[i]=do_work(data,i);});total=summarize(results,count);
Here, Dispatch_apply runs the passed block, puts each call in the global queue, and calls a different number from 0 to n-1 each time the block is called. This allows the operating system to allocate the appropriate work by selecting the optimal number of threads through the current hardware and system load. Dispatch_apply knows that all the blocks in a given queue will be completed before returning, so that everything in the original loop can be done before calling summarize. Programmers can create their own task queues, which must be executed serially, but can be executed in a separate thread. A new queue can be created like this:
12345 dispatch_queue_t exampleQueue;exampleQueue=dispatch_queue_create("com.example.unique.identifier",NULL);//exampleQueue may be used here.dispatch_release(exampleQueue);
Care must be taken to avoid the allocation of blocks in the queue that are synchronized in another block of the same queue, which guarantees that no deadlock condition will occur. Such code might do the following things:
123456789 dispatch_queue_t examplequeue=dispatch_queue_create ( ,null);  dispatch_sync (examplequeue,^{       dispatch_sync (examplequeue,^{           printf ( &NBSP;&NBSP;&NBSP;&NBSP;  dispatch_release (examplequeue);

IOS--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.