zoukankan      html  css  js  c++  java
  • GCD 学习(八)dispatch_semaphore

    dispatch_semaphore 信号量基于计数器的一种多线程同步机制。在多个线程访问共有资源时候,会因为多线程的特性而引发数据出错的问题。

        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);

        NSMutableArray *array = [NSMutableArrayarray];

        for (int index = 0; index < 100000; index++) {

            dispatch_async(queue, ^(){

                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);//

                NSLog(@"addd :%d", index);

                [array addObject:[NSNumber numberWithInt:index]];

                dispatch_semaphore_signal(semaphore);

            });

        }

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 如果semaphore计数大于等于1.计数-1,返回,程序继续运行。如果计数为0,则等待。这里设置的等待时间是一直等待。dispatch_semaphore_signal(semaphore);计数+1.在这两句代码中间的执行代码,每次只会允许一个线程进入,这样就有效的保证了在多线程环境下,只能有一个线程进入。

  • 相关阅读:
    logging日志模块
    mysql数据库--explain(查询表是否走索引)各个字段含义
    函数的命名空间、作用域、闭包函数
    模块
    Hibernate Stack Overflow
    PostgreSQL ----- No relations found.
    spring杂记
    JUnit test case 执行顺序
    转换成maven时报错
    参考网页
  • 原文地址:https://www.cnblogs.com/zhidao-chen/p/3600399.html
Copyright © 2011-2022 走看看