美文网首页
iOS中的GCD(三)

iOS中的GCD(三)

作者: jueyingxx | 来源:发表于2016-10-25 13:01 被阅读44次

dispatch_semaphore_t,信号量。

1、dispatch_semaphore_create创建一个信号量,然后初始化值为1,然后就可以调用dispatch_semaphore_wait方法了。

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);

2、dispatch_semaphore_wait,表示这个方法会一直等待,直到信号量的值大于等于1才会执行后面的代码。并且当执行完后,信号量的值会减1。
DISPATCH_TIME_FOREVER:是dispatch_time_t类型,表示永久。

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

3、dispatch_semaphore_signal,表示将信号量的值加1。

举个栗子:

- (void)test_dispatch_semaphore_concurrentQueue {
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.jueyingxx.concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    NSMutableArray *arr = @[].mutableCopy;
    for (NSInteger i = 0; i < 10000; i++) {
        dispatch_async(concurrentQueue, ^{
            // 1、当某个线程执行到这里,信号量为1的时候,那么wait方法返回1。开始执行接下来的操作,并且信号量的值变为减1,在这里变为0.其他的线程执行到这里都必须等待。
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            // 2、当执行完wait后,信号量变为0.可以执行之后的操作,其他的线程到wait这里都是返回0.所以都是等待状态。在这里对arr修改的线程,在任何时候都只有一个,所以是线程安全的。
            [arr addObject:[NSString stringWithFormat:@"%zi", i]];
            // 3、在所有操作结束后,调用下面的方法让信号量加1,如果有其他线程等待,则由最先等待的线程开始执行修改数组的操作。
            dispatch_semaphore_signal(semaphore);
        });
    }
    dispatch_barrier_async(concurrentQueue, ^{
        NSLog(@"%@", arr);
    });
}

相关文章

网友评论

      本文标题:iOS中的GCD(三)

      本文链接:https://www.haomeiwen.com/subject/epyruttx.html