zoukankan      html  css  js  c++  java
  • iOS信号量的使用

    并发多线程,多个资源的情况下,使用信号量。

    并发多线程,单个资源的情况下,使用mutex。

    6辆车,3个停车位的问题:

    -(void)testsemph{
        
        dispatch_semaphore_t semaphores = dispatch_semaphore_create(3);
        
        for(int i =0;i<6; i++)
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
                   dispatch_semaphore_wait( semaphores, DISPATCH_TIME_FOREVER);
                   NSLog(@" car %d input the plsition",i);
                   sleep(2);
                   dispatch_semaphore_signal(semaphores);
                   NSLog(@" car %d leave the plsition",i);
                   
               });
        }
        
        
    }
    2020-12-16 16:17:43.889732+0800 sempher[76427:2940388]  car 0 input the plsition
    2020-12-16 16:17:43.889811+0800 sempher[76427:2940389]  car 1 input the plsition
    2020-12-16 16:17:43.890044+0800 sempher[76427:2940390]  car 2 input the plsition
    2020-12-16 16:17:45.894960+0800 sempher[76427:2940389]  car 1 leave the plsition
    2020-12-16 16:17:45.895105+0800 sempher[76427:2940390]  car 2 leave the plsition
    2020-12-16 16:17:45.895478+0800 sempher[76427:2940391]  car 4 input the plsition
    2020-12-16 16:17:45.895506+0800 sempher[76427:2940387]  car 3 input the plsition
    2020-12-16 16:17:45.894954+0800 sempher[76427:2940388]  car 0 leave the plsition
    2020-12-16 16:17:45.895907+0800 sempher[76427:2940399]  car 5 input the plsition
    2020-12-16 16:17:47.900862+0800 sempher[76427:2940391]  car 4 leave the plsition
    2020-12-16 16:17:47.900900+0800 sempher[76427:2940399]  car 5 leave the plsition
    2020-12-16 16:17:47.901183+0800 sempher[76427:2940387]  car 3 leave the plsition
    
  • 相关阅读:
    Hoeffding Inequality 证明过程
    机器学习-1
    Java多线程安全问题的解决方式
    List<? extends T>和List<? super T>之间的区别
    关于禁用cookie后无法使用session的解决方案
    class.forName和classloader的区别
    在Js中使程序睡眠的sleep方法
    Java到底是值传递还是引用传递?
    Thymeleaf 绝对路径
    jdk1.8 Unsafe类 park和unpark方法解析
  • 原文地址:https://www.cnblogs.com/8335IT/p/14144639.html
Copyright © 2011-2022 走看看