The GCD of multi-threading tools

Source: Internet
Author: User
Tags gcd usleep

Grand Central Dispatch (GCD) is a solution for multi-core programming developed by Apple. With GCD, you do not need to manage threads, and thread management is fully managed to GCD. Written in plain C, generally use block to describe the first to understand the difference between synchronous and asynchronous, serial and parallel: synchronous: A request B task, only b task give a feedback, a can continue to execute asynchronous: A request B task, A no need to wait for a B response to proceed with the other Operation serial: One task completes the next task the dish may begin to parallel: at the same time, two tasks begin to execute, but do not interfere 1.dispatch QueueThe dispatch queue is divided into the following three types: 1) running the main queue in the main thread, obtained through Dispatch_get_main_queue. 2) Parallel Queue Global dispatch queue (can be multiple threads parallel, task can be executed simultaneously), Dispatch_get_global_queue obtained by the system to create three different priority dispatch queue. Parallel queues are executed in the same order as they join the queue. 3) Serial Queue serial queues (all threads are serial, or only one thread, the task executes sequentially) is typically used to synchronize access sequentially, creating any number of serial queues, which are concurrent between each serial queue.

Serial queues are useful when you want tasks to execute in a particular order. A serial queue performs only one task at a time. We can use serial queues instead of locks to protect shared data. Unlike locks, a serial queue guarantees that the task executes in a predictable order.

Serial queues is created through dispatch_queue_create and can be used to increase or decrease the reference count using function Dispatch_retain and dispatch_release.
Create a serial queue//The first parameter represents the name of the queue, and the second parameter represents the type of the queue
dispatch_queue_t queue_1 = dispatch_queue_create ("queue.1", dispatch_queue_serial);
Create a parallel queue dispatch_queue_t queue_2 = dispatch_queue_create ("queue.2", dispatch_queue_concurrent);
Gets the global concurrent queue (which belongs to the parallel queues)
The first parameter represents a priority, and the second parameter is temporarily useless dispatch_queue_t global_queue = Dispatch_get_global_queue (dispatch_queue_priority_default , 0);
The queue that gets the management main thread (which is part of the serial queue)//and the task that is submitted to the main queue may not be executed immediately, but will not be executed until the main thread's run loop detects a task that has dispatch submitted dispatch_queue_t Main_q Ueue = Dispatch_get_main_queue ();
  2. Submit a Task divided into two types: synchronous commit and asynchronous commitTwo parameters:. The first parameter represents the queue that is submitted to. The second parameter represents the task details, which describes a task in block mode, for the simple reason that block is a pure C implementation, while the usual invocation or target+selector approach is object-oriented.  
Gets the globally concurrent queue
dispatch_queue_t global_queue = dispatch_get_global_queue (dispatch_queue_priority_default, 0); 1. Synchronous commit//if using synchronous request mode, it will result in the death of the current thread.
after the task is submitted synchronously, the block is executed first , and then dispatch_sync () returns
Dispatch_sync (Global_queue, ^{
NSLog (@ "do something");
});
NSLog (@ "OK");
2. After the asynchronous commit// Asynchronous Commit task , the Dispatch_async () function returns directly without waiting for block Execution ends .
Dispatch_async (Global_queue, ^{
NSLog (@ "do something ...");
}); NSLog (@ "OK ...");
3. Simultaneous submission of multiple tasks dispatch_queue_t queue_1 = dispatch_queue_create ("queue.1", dispatch_queue_serial); dispatch_queue_t queue_2 = dispatch_queue_create ("queue.2", dispatch_queue_concurrent);

Number of tasks
size_t count = 10;

Submit multiple Tasks synchronously
Three parameters are: task count, target queue, task description
//if the target queue is serial , then the task executes sequentially if the queue is parallel , the task is executed concurrently and the order of printing is disrupted
Dispatch_apply (count, queue_2, ^ (size_t i) {
NSLog (@ "%zu", I);
});
NSLog (@ "---OK---"); Compare synchronous commit multiple tasks and iterate over an array which is fast (without caring for the array order)//traversing the array
nsmutablearray* array = [[Nsmutablearray alloc]initwithcapacity:1000];

for (int i =0; i<1000; i++) {
[Array addobject:[nsstring stringwithformat:@ "%d", I]];

}
NSLog (@ "Start Forin");//array traversal for (nsstring* A in array) {
NSLog (@ "--%@", a);
} NSLog (@ "fisined Forin"); NSLog (@ "start apply");//Simultaneous submission of multiple tasks dispatch_apply (Array.count, queue_2, ^ (size_t i) {
NSLog (@ "%@", Array[i]);
}); NSLog (@ "fisined apply");
  3. DeadlockA synchronous commit can cause a deadlock in some cases, that is, the card dies.
Main thread (belongs to serial queue) deadlock//will not print anything dispatch_queue_t main_queue = Dispatch_get_main_queue (); Synchronous execution Dispatch_sync (Main_queue, ^{
NSLog (@ "-----");
}); NSLog (@ "OK"); The program by default is executed from top to bottom, but when the program goes to Dispatch_sync, it will go to block and then return to Dispatch_sync, so it will collide and form a deadlock .
   //serial queue
    dispatch_queue_t queue_1 = dispatch_queue_create ("Queue.1", Dispatch_queue_serial);
   //Asynchronous Commit
    Dispatch_async (queue_1, ^{
      &NBSP
       //will not be printed
       // Synchronous commit
        Dispatch_sync (queue_1, ^{
             NSLog (@ "BBB");
       });
        NSLog (@ "CCCCC");
       
   });
       NSLog (@ "AAAA");   
Deadlock resolution: serial queues are executed asynchronously and parallel queues are executed synchronously. in a serial queue , a deadlock occurs when the task is synchronously committed to its own queue. To change the serial queue to a parallel queue without a deadlock, or to change the synchronous commit task to asynchronous commit.        
4.Dispatch Group What is Dispatch group, as we add dependencies in Nsoperation, if one of our tasks needs to wait for some other task to finish to execute 4.1 Submitting a taskIs divided into two steps:1. Create group2. Submit the task and add the task to group
1. Create Group dispatch_group_t group = Dispatch_group_create (); dispatch_queue_t global_queue = dispatch_get_global_queue (dispatch_queue_priority_default, 0)
//2. Submit a task to global_queue, and add it to group           //global_queue is not a queue, But group must be the same          //group only asynchronous commit, no synchronous commit     Dispatch_group_async (group, Global_queue, ^{
       
        Usleep (10000);
        NSLog (@ "buy pot");
       
   });
   
    dispatch_group_async (Group, global_queue, ^{
         Usleep (10000);
        NSLog (@ "buy vegetables");
       
   });
   
    dispatch_group_async (Group, global_queue, ^{
         Usleep (10000);
        NSLog (@ "Buy drinks");   });
3. Asynchronously submit the ultimate task to the queue, Main_queue//The ultimate task is equivalent to operation1 dependent on Operation2, just operation1 cannot be the same as the previous task, but requires the ultimate task Dispatch_ Group_notify Commit//asynchronous commit does not block the current thread//to block the current thread, waiting for the group to end all tasks, need to use the Dispatch_group_wait dispatch_group_notify (group, DIS Patch_get_main_queue (), ^{
NSLog (@ "Eat hotpot");
});
Create dispatch time//You can customize the timeout period, wait for a certain period dispatch_time_t time = Dispatch_time (Dispatch_time_now, (int64_t) ($ * nsec_ PER_SEC));     4. Custom timeout//set timeout, block current thread dispatch_group_wait (group, time); The time to buy a drink is too long, it is more than the waiting time, so it is difficult to execute NSLog (@ "...");
NSLog (@ "watch TV");

The GCD of multi-threading tools

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.