作者whitefur (白毛)
看板MacDev
標題[問題] dispatch semaphore
時間Wed Aug 28 12:31:22 2013
1 __block dispatch_semaphore_t sem = dispatch_semaphore_create ( 0 ) ;
2
3 dispatch_queue_t queue = dispatch_queue_create ( "firstQueue" , nil ) ;
4 dispatch_async ( queue, ^ ( void ) {
5 sleep ( 2 - i / 50 ) ;
6 NSLog ( @ "The sum is: %d" , i ) ;
7
8 // signal the semaphore
9 dispatch_semaphore_signal ( sem ) ;
10 } ) ;
11
12 // wait for the semaphore
13 dispatch_semaphore_wait ( sem, DISPATCH_TIME_FOREVER ) ;
14
15 dispatch_release ( queue ) ;
看完apple的文件
只大概了解semaphore是一個lock的機制
dispatch_semaphore_wait會將semaphore 減 1
如果semaphore的值為小於0時
則其它process就暫時不能access該resource
dispatch_semaphore_signal則會將semaphore 加 1
想問說這個概念套用到上面的程式碼的邏輯是什麼?
semaphore針對的resource是程式碼的哪個區塊?
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.230.131.203
→ popcorny:A叫B做事 然後A等B B做完了告訴A A繼續往下走 08/28 13:03
→ whitefur:所以A跟B是在程式碼的哪個位置 08/28 14:25
※ 編輯: whitefur 來自: 114.36.63.187 (08/28 14:26)
※ 編輯: whitefur 來自: 114.36.63.187 (08/28 14:27)
→ popcorny:5-10這邊都是B 其他是A 08/28 15:23
→ whitefur:執行到dispatch_semaphore_wait時就停下來 08/28 17:06
→ whitefur:等到dispatch_semaphore_signal時, A才能再繼續往下走 08/28 17:07
→ whitefur:是這個意思嗎 08/28 17:08
→ popcorny:yes.. 就是這個意思 08/28 22:14