当前位置: 首页>编程语言>正文

dispatch_semaphore_t

dispatch_semaphore_t :信号量
包含三个函数:
1、创建信号量

dispatch_semaphore_create(intptr_t value);
//value 需大于等于0

2、增加信号量

dispatch_semaphore_signal(dispatch_semaphore_t dsema);

3、削减信号量

dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout);
//当信号量值为0时,则会进入等待,后面的代码不会执行

注意:当dispatch_semaphore_create传的值假设为N时,最终semaphore释放时的值,要求大于或等于N,不然会爆异常"BUG IN CLIENT OF LIBDISPATCH: Semaphore object deallocated while in use"

简单应用
1、假设有事件A、B,要求A先执行完,再执行B

- (void)testSemaphore {
    _semaphore = dispatch_semaphore_create(1);
    dispatch_queue_t que = dispatch_queue_create("myque", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(que, ^{
        [self doAThings];
    });
    dispatch_async(que, ^{
        [self doBThings];
    });
 }

- (void)doAThings {
    //进入时,信号量为1,减1后继续执行
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"做A做的活,让B等着吧");
    sleep(5);
    dispatch_semaphore_signal(_semaphore);
}

- (void)doBThings {
    //进入时,信号量为0,需等待上方dispatch_semaphore_signal +1,才能接着执行
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"大家好,我是Boy,B!");
}

执行结果:

2022-09-01 18:20:58.358760+0800 asnkjfhew9f[2558:112841] 做A做的活,让B等着吧
2022-09-01 18:21:03.360169+0800 asnkjfhew9f[2558:113488] 大家好,我是Boy,B!

但是,这种只能控制只有两个事件的执行先后顺序。

2、假设有事件N个,要求按顺序先后执行,则需要搭配串行队列

- (void)serialRunThings {
    _semaphore = dispatch_semaphore_create(1);
    //串行队列
    dispatch_queue_t que = dispatch_queue_create("myque", DISPATCH_QUEUE_SERIAL);
    for (int i = 0; i < 1000; i++) {
        dispatch_async(que, ^{
            [self run:@(i)];
        });
    }
}

- (void)run:(NSNumber *)i {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"--%@--",i);
    sleep(0.3);
    dispatch_semaphore_signal(_semaphore);
 }

执行结果:

2022-09-01 18:23:05.516694+0800 asnkjfhew9f[2603:114826] --0--
2022-09-01 18:23:05.516694+0800 asnkjfhew9f[2603:114826] --1--
2022-09-01 18:23:05.516694+0800 asnkjfhew9f[2603:114826] --2--
2022-09-01 18:23:05.516694+0800 asnkjfhew9f[2603:114826] --3--
.......
2022-09-01 18:23:05.516694+0800 asnkjfhew9f[2603:114826] --996--
2022-09-01 18:23:05.516954+0800 asnkjfhew9f[2603:114826] --997--
2022-09-01 18:23:05.517209+0800 asnkjfhew9f[2603:114826] --998--
2022-09-01 18:23:05.517338+0800 asnkjfhew9f[2603:114826] --999--

https://www.xamrdz.com/lan/5xs2016266.html

相关文章: