[問題] dispatch semaphore

看板MacDev作者 (白毛)時間12年前 (2013/08/28 12:31), 編輯推噓0(007)
留言7則, 2人參與, 最新討論串1/1
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

08/28 13:03, , 1F
A叫B做事 然後A等B B做完了告訴A A繼續往下走
08/28 13:03, 1F

08/28 14:25, , 2F
所以A跟B是在程式碼的哪個位置
08/28 14:25, 2F
※ 編輯: whitefur 來自: 114.36.63.187 (08/28 14:26) ※ 編輯: whitefur 來自: 114.36.63.187 (08/28 14:27)

08/28 15:23, , 3F
5-10這邊都是B 其他是A
08/28 15:23, 3F

08/28 17:06, , 4F
執行到dispatch_semaphore_wait時就停下來
08/28 17:06, 4F

08/28 17:07, , 5F
等到dispatch_semaphore_signal時, A才能再繼續往下走
08/28 17:07, 5F

08/28 17:08, , 6F
是這個意思嗎
08/28 17:08, 6F

08/28 22:14, , 7F
yes.. 就是這個意思
08/28 22:14, 7F
文章代碼(AID): #1I7NqSLX (MacDev)
文章代碼(AID): #1I7NqSLX (MacDev)