zoukankan      html  css  js  c++  java
  • iOS 线程同步-信号量 dispatch_semaphore

    #define kSemaphoreBegin 
    static dispatch_semaphore_t semaphore; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        semaphore = dispatch_semaphore_create(1); 
    }); 
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    #define kSemaphoreEnd 
    dispatch_semaphore_signal(semaphore);
    #import "ViewController.h"
    @interface ViewController ()
    @property (nonatomic,assign)  int ticket;
    @property (nonatomic, strong) dispatch_semaphore_t semaphore;
    @property (nonatomic, strong) dispatch_semaphore_t semaphore1;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.semaphore = dispatch_semaphore_create(1);//最多1个线程同时执行
            self.semaphore1 = dispatch_semaphore_create(5);//最多1个线程同时执行
        self.ticket=50;
        [self ticketsTest];
    //    for (int i = 0 ; i<20; i++) {
    //        [[[NSThread alloc]initWithTarget:self selector:@selector(test2) object:nil] start];
    //    }
        // Do any additional setup after loading the view.
    }
    -(void)test2{
        /*
          执行semaphore_wait 如果semaphore1 >0  semaphore1的值就会减一 并继续往下执行
         如果semaphore1 <=0 线程就会休眠 直到 semaphore1的值>0 再将semaphore1的值就会减一 并继续往下执行
         */
        dispatch_semaphore_wait(self.semaphore1, DISPATCH_TIME_FOREVER);
        sleep(2);
        NSLog(@"test");
        //信号量的值加一
        dispatch_semaphore_signal(self.semaphore1);
    }
    -(void)saleTicket{
    //    static dispatch_semaphore_t semaphore;
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    //        semaphore=dispatch_semaphore_create(1);
    //    });
    //    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    //    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
        kSemaphoreBegin
            int ticket = self.ticket;
            sleep(.2);
            ticket--;
            self.ticket=ticket;
            NSLog(@"%d-=%@",self.ticket,[NSThread currentThread]);
        kSemaphoreEnd
    //    dispatch_semaphore_signal(semaphore);
    //    dispatch_semaphore_signal(self.semaphore);
    }
    -(void)ticketsTest{
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            for (int i =0; i<5; i++) {
                [self saleTicket];
            }
        });
        dispatch_async(queue, ^{
            for (int i =0; i<5; i++) {
                [self saleTicket];
            }
        });
    }
    @end
  • 相关阅读:
    图片预加载的JS代码
    JavaScript实现漫天飞花及文字滚动特效的代码
    判断远程图片是否存在的JavaScript代码
    dos批处理命令详解
    内存虚拟盘软件XMSDSK的使用
    医学论坛(收集)
    velocity
    java开源项目 源代码
    开放源代码的全文检索引擎Lucene
    批处理命令大全
  • 原文地址:https://www.cnblogs.com/ZhangShengjie/p/12292066.html
Copyright © 2011-2022 走看看