版權聲明:本文爲博主原創文章,未經博主容許不得轉載。編程
簡單的介紹一下這三個函數,第一個函數有一個整形的參數,咱們能夠理解爲信號的總量,dispatch_semaphore_signal是發送一個信號,天然會讓信號總量加1,dispatch_semaphore_wait等待信號,當信號總量少於0的時候就會一直等待,不然就能夠正常的執行,並讓信號總量-1,根據這樣的原理,咱們即可以快速的建立一個併發控制來同步任務和有限資源訪問控制多線程
int data = 3;併發
__block int mainData = 0;async
__block dispatch_semaphore_t sem = dispatch_semaphore_create(0);函數
dispatch_queue_t queue = dispatch_queue_create("StudyBlocks", NULL);post
dispatch_async(queue, ^(void) {ui
int sum = 0;spa
for(int i = 0; i < 5; i++).net
{線程
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以後執行