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
    
  • 相关阅读:
    log4j学习总结
    MAVEN工程生成可执行的jar包
    从svn上下载maven项目import cannot resolved
    junit4使用说明
    uml中箭头的意思
    maven命令
    mavenSvn
    ASP.NET MVC学习笔记:(二)return View(...)
    WPF学习笔记:(一)数据绑定与DataContext
    WCF学习笔记(五):svc、config和code文件之间的关系
  • 原文地址:https://www.cnblogs.com/8335IT/p/14144639.html
Copyright © 2011-2022 走看看