作者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
1F:→ popcorny:A叫B做事 然後A等B B做完了告诉A A继续往下走 08/28 13:03
2F:→ 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)
3F:→ popcorny:5-10这边都是B 其他是A 08/28 15:23
4F:→ whitefur:执行到dispatch_semaphore_wait时就停下来 08/28 17:06
5F:→ whitefur:等到dispatch_semaphore_signal时, A才能再继续往下走 08/28 17:07
6F:→ whitefur:是这个意思吗 08/28 17:08
7F:→ popcorny:yes.. 就是这个意思 08/28 22:14