zoukankan      html  css  js  c++  java
  • 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.在这两句代码中间的执行代码,每次只会允许一个线程进入,这样就有效的保证了在多线程环境下,只能有一个线程进入。

  • 相关阅读:
    使用telnet模拟http请求
    07_Python变量内存地址、小数据池
    04_Linux命令
    03_Linux文件和目录
    06_Python Encoded
    05_Python Format Operation
    04_Python Data Structures
    02_Python基本数据类型
    01_软件开发流程
    03_线性表应用一:栈
  • 原文地址:https://www.cnblogs.com/wudan7/p/3910382.html
Copyright © 2011-2022 走看看