dispatch_semaphore_signal和dispatch_semaphore_wait信号量

来源:互联网 发布:360压缩 mac 编辑:程序博客网 时间:2024/05/23 00:04
来一个例子
-(void)testSegiel{    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);  //0    NSMutableArray *array = [NSMutableArray array];        for (int index = 0; index < 10; index++) {                dispatch_async(queue, ^(){                        NSLog(@"quene :%d", index);//1                        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);                        NSLog(@"addd :%d", index);//2                        [array addObject:[NSNumber numberWithInt:index]];                        dispatch_semaphore_signal(semaphore);                    });            }}

进行打印看结果,

2016-08-25 19:08:36.599 testNew[2880:2514251] async--->>>0

2016-08-25 19:08:36.599 testNew[2880:2513974] async--->>>1

2016-08-25 19:08:36.600 testNew[2880:2514252] async--->>>2

2016-08-25 19:08:36.600 testNew[2880:2514253] async--->>>3

2016-08-25 19:08:36.600 testNew[2880:2514254] async--->>>4

2016-08-25 19:08:36.600 testNew[2880:2514251] semaphore:0

2016-08-25 19:08:36.600 testNew[2880:2514255] async--->>>5

2016-08-25 19:08:36.600 testNew[2880:2514256] async--->>>6

2016-08-25 19:08:36.601 testNew[2880:2514251] async--->>>7

2016-08-25 19:08:36.601 testNew[2880:2514255] semaphore:5

2016-08-25 19:08:36.601 testNew[2880:2514257] async--->>>8

2016-08-25 19:08:36.601 testNew[2880:2514255] async--->>>9

2016-08-25 19:08:36.601 testNew[2880:2514252] semaphore:2

2016-08-25 19:08:36.601 testNew[2880:2514253] semaphore:3

2016-08-25 19:08:36.601 testNew[2880:2514254] semaphore:4

2016-08-25 19:08:36.601 testNew[2880:2513974] semaphore:1

2016-08-25 19:08:36.601 testNew[2880:2514256] semaphore:6

2016-08-25 19:08:36.602 testNew[2880:2514251] semaphore:7

2016-08-25 19:08:36.602 testNew[2880:2514257] semaphore:8

2016-08-25 19:08:36.602 testNew[2880:2514255] semaphore:9


发现全部执行

就能看到其中1部分全部基本是顺序执行,2部分无序执行。

如果把是dispatch_semaphore_create(1)改成dispatch_semaphore_create(0)的话

就能看到其中1部分全部基本是顺序执行,2部分一直没有执行。

因为dispatch_semaphore_wait是进行信号量减1操作,而dispatch_semaphore_signal是进行加1操作。如果dispatch_semaphore_wait减1前如果小于1,则一直等待。同时这两者之间是线程无顺序的抢占资源,但只能允许一个线程执行。所以猜测如果某一时刻进行了dispatch_semaphore_signal操作,则会继续执行

0 0