• 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
    
  • 相关阅读:
    简明python教程九----异常
    简明python教程八----输入/输出
    简明python教程七----面向对象的编程(下)
    vue --- 生命周期
    es6 ----- export 和 import
    jq ---- 实现浏览器全屏
    Vue项目自动转换 px 为 rem,高保真还原设计图
    vue ---- 实现手机端(左滑 删除。右划 正常)
    js---- localStorage的基本用法
    点击 下载文件保存
  • 原文地址:https://www.cnblogs.com/8335IT/p/14144639.html
Copyright © 2020-2023  润新知