In the previous GCD, the semaphore mechanism describes the number of parallel maximum threads set by the semaphore, which can also prevent multithreading from accessing public variables when the data is incorrect, as the following code illustrates.
1. The following is a value that does not use semaphores to modify public variables
dispatch_group_t group=dispatch_group_create ();// dispatch_semaphore_t semaphore=dispatch_semaphore_create (1 ); dispatch_queue_t queue=dispatch_get_global_queue (dispatch_queue_priority_default, 0); __block int count=1000; for (int i=0; i<100; i++) { //signal volume minus 1, if more than 10 threads are turned on at the same time, the semaphore is less than or equal to 0, and the thread is blocked at this time. dispatch_semaphore_wait (semaphore, dispatch_time_forever); Dispatch_group_async (group, queue, ^{ int value = (arc4random ()% 4) + 6; NSLog (@ "%d-%d=%d", count,value,count-value); Count=count-value; Each thread executes minus 1 by a semaphore notification plus 1, so that the thread is always kept within 10// dispatch_semaphore_signal (semaphore); }); } Dispatch_group_wait (group, dispatch_time_forever);
2. The results of the operation are as follows:
3. Declare a semaphore with an initial value of 1 to open the thread when modifying a public variable
dispatch_group_t group=dispatch_group_create (); dispatch_semaphore_t semaphore=dispatch_semaphore_create (1); dispatch_queue_t queue=dispatch_get_global_queue (dispatch_queue_priority_default, 0); __block int count=1000; for (int i=0; i<100; i++) { //signal volume minus 1, if more than 10 threads are turned on at the same time, the semaphore is less than or equal to 0, and the thread is blocked at this time. dispatch_semaphore_wait (semaphore, dispatch_time_forever); Dispatch_group_async (group, queue, ^{ int value = (arc4random ()% 4) + 6; NSLog (@ "%d-%d=%d", count,value,count-value); Count=count-value; Each thread executes minus 1 by a semaphore notification plus 1, so that the thread is always kept within 10 dispatch_semaphore_signal (semaphore); }); } Dispatch_group_wait (group, dispatch_time_forever);
4. The results of the operation are as follows:
As you can see, the first code snippet is not ordered when the public variable is modified, and the second snippet is the true correct order of modification. This process can be withdrawn as the process, the amount is 1000, may be in different places at the same time withdrawals, withdrawals can not be the amount of money as the first code snippet. This has the same effect as the C # lock keyword.
GCD Signaling Mechanism II