1. GCD: One of the techniques for executing tasks asynchronously is to implement the thread management code described in the application at the system level , because it is managed at the system level, so that there will be better threading efficiency.
2. Use the following methods:
Dispatch_async (queue, ^{ //Want to perform the task});
The only thing developers need to do is define the tasks they want to perform and append them to the appropriate dispatch queue.
3. Thread: 1 CPU instructions executed by CPUs are listed as a non-forked path.
4. The Dispatch queue is divided into two types:
A. Serial Dispatch queue: Thread queuing for linear execution, followed by FIFO (first first out) principle;
B. Concurrent Dispatch queue: Concurrent execution of thread queues, the number of concurrent executions depends on the current state.
Linear execution Thread queue dispatch_queue_t serialqueue = dispatch_queue_create ("Com.mark.serialQueue", NULL);d Ispatch_async ( Serialqueue, ^{ NSLog (@ "block on Serialqueue"); Dispatch_release (serialqueue);//concurrent Execution thread queue dispatch_queue_t concurrentqueue = Dispatch_queue_create (" Com.mark.concurrentQueue ", dispatch_queue_concurrent);d Ispatch_async (concurrentqueue, ^{ NSLog (@" block on Concurrentqueue ");}); Dispatch_release (Concurrentqueue);
5. Dispatch Queue for the system:
A. Main Dispatch queue: Main thread queues (Serial), executed in Runloop of the program.
B. Global Dispatch queue: Concurrent queue, which is common to all applications in the system, does not normally have to create a new Dispatch queue, which is available with this queue.
The Global DIAPACTH queue has 4 priority levels: high, default, low, and Background (background).
Get main Dispatch queuedispatch_queue_t maindispatchqueue = Dispatch_get_main_queue ();//Get Global Dispatch queuedispatch_queue_t Globaldispatchqueuehigh = dispatch_get_global_queue (dispatch_queue_priority_high, 0); dispatch_queue_t Globaldispatchqueuedefault = dispatch_get_global_queue (dispatch_queue_priority_default, 0); dispatch_queue_t Globaldispatchqueuelow = dispatch_get_global_queue (dispatch_queue_priority_low, 0);d Ispatch_queue _t Globaldispatchqueuebackground = dispatch_get_global_queue (dispatch_queue_priority_background, 0);//Common Example dispatch _async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{ //execute concurrent processing dispatch_async ( Dispatch_get_main_queue (), ^{ //Perform the main thread update operation });
6. About the Dispatch queue priority for custom builds: first the Dispatch queue generated by dispatch_queue_create () has the same precedence as the default global Dispatch queue. To change the priority of the dispatch queue, use the Dispatch_set_target_queue function:
Change Serialqueue (Default priority) to background prioritydispatch_queue_t Serialqueue = Dispatch_queue_create (" Com.mark.serialQueue ", NULL);d ispatch_queue_t globaldispatchqueuebackground = Dispatch_get_global_queue (dispatch_ Queue_priority_background, 0);d ispatch_set_target_queue (Serialqueue, Globaldispatchqueuebackground);
7. Deferred execution of the Dispatch queue: Dispatch_after ():
Adds the specified block to the specified dispatch queue after 2 seconds double delayinseconds = 2.0;dispatch_time_t Poptime = Dispatch_time (dispatch_time_ Now, (int64_t) (Delayinseconds * nsec_per_sec));d ispatch_after (Poptime, Dispatch_get_main_queue (), ^ (void) { NSLog (@ "waitted at least 2 Seconds");});
8. Execution after completion of multiple Dispatch queue execution: Dispatch Group
dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority_default, 0);d ispatch_group_t group = Dispatch_group_create ();d ispatch_group_async (group, queue, ^{ NSLog (@ "queue one");}); Dispatch_group_async (group, queue, ^{ NSLog (@ "queue");}); Dispatch_group_async (group, queue, ^{ NSLog (@ "queue three");}); Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{ NSLog (@ "Queues done");});
You can also do this, with each two parameter indicating the time-out
Dispatch_group_wait (group, dispatch_time_forever);
dispatch_time_t time = Dispatch_time (Dispatch_time_now, 1ull *nsec_per_sec);
Long result = Dispatch_group_wait (group, time);
if (0 = = result) {
All processing execution ends belonging to dispatch group
}
else {
A process belonging to the dispatch group is still in execution after a specified time limit is exceeded
}
Dispatch_release (group);
However, it is recommended to use Dispatch_group_notify
9. Data synchronization for Read and write operations, for data processing: Dispatch_barrier_async ()
dispatch_queue_t queue = dispatch_queue_create ("Com.mark.queue", Dispatch_queue_concurrent);d Ispatch_async (queue, bk_0_for_reading);d ispatch_async (queue, bk_1_for_reading);d ispatch_async (queue, bk_2_for_reading);d Ispatch_async (queue, bk_3_for_reading);//The concurrent queues above are read tasks and do not involve data conflict issues (data can be read at the same time by multiple threads, concurrently used to improve efficiency and does not affect data)// Next is the concurrent Queue task Dispatch_barrier_async (queue, bk_for_writing) that is to be written before performing the associated lower half, and//continues the lower part of the Concurrency Dispatch_async (queue, bk_4_ for_reading);d ispatch_async (queue, bk_5_for_reading);d ispatch_async (queue, bk_6_for_reading);
10. Block Api:dispatch_apply () that can control the number of Dispatch_async block blocks executed
dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority_default, 0);d ispatch_apply (, queue, ^ ( size_t index) { NSLog (@ "%zu", Index);}); /param1:block number of executions//param2:block//Param3:block Execution Index///efficient traversal of data elements (unordered traversal) dispatch_queue_t queue = Dispatch_get_g Lobal_queue (dispatch_queue_priority_default, 0);d ispatch_apply ([array count], queue, ^ (size_t index) { NSLog (@ " Array element of index%d:%@ ", index, [array Objectatindex:index]);});
11. Thread queue Suspend and execute:
Suspend queue dispatch_suspend (queue);//Resume Queue execution Dispatch_resume (queue);
12. Finer-Grained exclusive controls: Dispatch_semaphore
1 dispatch_queue_t queue = dispatch_get_global_queue (Dispatch_queue_priority_default, 0); 2//Create Dispatch_semaphore 3//Semaphore value initialized to 1 4//guaranteed access to Nsmutablearray class object with only one 5 dispatch_semaphore_t semap Hore = dispatch_semaphore_create (1); 6 Nsmutablearray *array = [[Nsmutablearray alloc] init]; 7 for (int i = 0; i < 100000; i++) {8 Dispatch_async (queue, ^{9//Waiting for dispatch semaphore until SEMA Phore value is greater than or equal to dispatch_semaphore_wait (semaphore, dispatch_time_forever); 11//due to dispatch semaphore count value reached Greater than or equal to 112//So the count value of dispatch semaphore is reduced 113//dispatch_semaphore_wait function Execution returns 14//The dispatch SEM that executes to this time Aphore count value constant is 015//Because the thread that can access the Nsmutablearray class object has only one 16//So it can be safely updated by [array addobject:[nsnumber number WITHINT:I]];18//Exclusive control processing end 19//So by dispatch_semaphore_signal function 20//will dispatch semaphore count value Plus 121 If there is a thread that is incremented by the dispatch_semaphore_wait function waiting for the 22//Count value of dispatch semaphore, executed by the first waiting thread dispatch_semaphore_signal (semaphore);}26 Dispatch_release (semaphore);
Dispatch_once: Execute only one API for the specified processing
The Dispatch_once function is simplified as follows: static int initialized = No;if (NO = = initialized) { //initialize initialized = YES;} The Dispatch_once function uses the following static dispatch_once_t Pred;dispatch_once (&pred, ^{ //initialization, which is used here for Singleton mode});
Dispatch I/O: Read file data concurrently, read files efficiently:
Concurrent Read file principle Dispatch_async (queue, ^{/* reads 0-8191 bytes */});d Ispatch_async (queue, ^{/* read 8192-16383 bytes */});d Ispatch_async ( Queue, ^{/* reads 163784-24575 bytes */});d Ispatch_async (queue, ^{/* reads 24576-32767 bytes */});d Ispatch_async (queue, ^{/* Read 32768-40959 bytes */});d Ispatch_async (queue, ^{/* read 40960-49151 bytes */});d Ispatch_async (queue, ^{/* read 49152-57343 bytes */}); Dispatch_async (queue, ^{/* reads 57344-65535 bytes */});//The instance code is as follows dispatch_queue_t pipe_q = Dispatch_queue_create ("PipQ", NULL) ;d ispatch_io_t Pipe_channel = dispatch_io_create (Dispatch_io_stream, FD, PIP_Q, & (int err) {close (FD);}); *OUT_FD = dfpair[1];//Set function one read size (split size) dispatch_io_set_low_water (Pipe_channel, Size_max);d Ispatch_io_read (pipe_ Channel, 0, Size_max, pipe_q, ^{if (0 = = Err) {size_t len = dispatch_data_get_size (pipedata); if (Len > 0) {const char *bytes = NULL; Char *encoded; dispatch_data_t MD = Dispatch_data_create_map (pipedata, (const void * *) &bytes, &len); encoded = Asl_Core_encode_buffer (bytes, Len); Asl_set ((aslmsg) merged_msg, asl_key_aux_data, encoded); Free (encoded); _asl_send_message (NULL, MERGED_MSG,-1, NULL); _asl_msg_release (MERGED_MSG); Dispatch_release (MD); }} if (done) {dispatch_semaphore_signal (SEM); Dispatch_release (Pipe_channel); Dispatch_release (PIPE_Q); }});
GCD (Grand Central Dispatch)