A semaphore is an integer value and has an initial count value, and supports two operations: signaling and waiting. When a semaphore is signaled, its count is incremented. When a thread waits on a semaphore, the thread is blocked (if necessary) until the counter is greater than zero, and then the thread decrements the count.
There are three functions in GCD that are semaphore operations, namely:
dispatch_semaphore_create to create a semaphore
dispatch_semaphore_signal to send a signal
dispatch_semaphore_wait to wait for a signal
Briefly introduce these three functions. The first function has an integer parameter, which we can understand as the total amount of signals. dispatch_semaphore_signal is to send a signal, which will naturally increase the total amount of signals by 1. dispatch_semaphore_wait waits for the signal. When the amount is less than 0, it will keep waiting, otherwise it can be executed normally, and let the total number of signals -1. According to this principle, we can quickly create a concurrency control to synchronize tasks and limited resource access control.
int data = 3;
__block int mainData = 0;
__block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_queue_create("StudyBlocks", NULL);
dispatch_async(queue, ^(void) {
int sum = 0;
for(int i = 0; i < 5; i++)
{
sum += data;
NSLog(@" >> Sum: %d", sum);
}
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
for(int j=0;j<5;j++)
{
mainData++;
NSLog(@">> Main Data: %d",mainData);
}
dispatch_release(sem);
dispatch_release(queue);
2013-07-08 11:33:05.654 dispatch[1102:1e03] >> Sum: 3
2013-07-08 11:33:05.656 dispatch[1102:1e03] >> Sum: 6
2013-07-08 11:33:05.657 dispatch[1102:1e03] >> Sum: 9
2013-07-08 11:33:05.658 dispatch[1102:1e03] >> Sum: 12
2013-07-08 11:33:05.659 dispatch[1102:1e03] >> Sum: 15
2013-07-08 11:33:05.660 dispatch[1102:c07] >> Main Data: 1
2013-07-08 11:33:05.660 dispatch[1102:c07] >> Main Data: 2
2013-07-08 11:33:05.660 dispatch[1102:c07] >> Main Data: 3
2013-07-08 11:33:05.661 dispatch[1102:c07] >> Main Data: 4
2013-07-08 11:33:05.661 dispatch[1102:c07] >> Main Data: 5
通过信号量就可以保证,Main Data 永远在Sum之后执行