iOS信号量详解

一、信号量的简单介绍:

1.信号量:

        信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施,是可以用来保证两个或多个关键代码段不被并发调用。在进入一个关键代码段之前,线程必须获取一个信号量;一旦该关键代码段完成了,那么该线程必须释放信号量。其它想进入该关键代码段的线程必须等待直到第一个线程释放信号量。为了完成这个过程,需要创建一个信号量VI,然后将Acquire Semaphore VI以及Release Semaphore VI分别放置在每个关键代码段的首末端。确认这些信号量VI引用的是初始创建的信号量。

2.特性:

         抽象的来讲,信号量的特性如下:信号量是一个非负整数(车位数),所有通过它的线程/进程(车辆)都会将该整数减一(通过它当然是为了使用资源),当该整数值为零时,所有试图通过它的线程都将处于等待状态。在信号量上我们定义两种操作: Wait(等待) 和 Release(释放)。当一个线程调用Wait操作时,它要么得到资源然后将信号量减一,要么一直等下去(指放入阻塞队列),直到信号量大于等于一时。Release(释放)实际上是在信号量上执行加操作,对应于车辆离开停车场,该操作之所以叫做“释放”是因为释放了由信号量守护的资源。

3.描述:

        以一个停车场的运作为例。简单起见,假设停车场只有三个车位,一开始三个车位都是空的。这时如果同时来了五辆车,看门人允许其中三辆直接进入,然后放下车拦,剩下的车则必须在入口等待,此后来的车也都不得不在入口处等待。这时,有一辆车离开停车场,看门人得知后,打开车拦,放入外面的一辆进去,如果又离开两辆,则又可以放入两辆,如此往复。
在这个停车场系统中,车位是公共资源,每辆车好比一个线程,看门人起的就是信号量的作用。

4.发展史:

       1965年,荷兰学者Edsger Dijkstra提出的信号量(Semaphores)机制是一种卓有成效的进程同步工具,在长期广泛的应用中,信号量机制得到了极大的发展,它从整型信号量经记录型信号量,进而发展成为“信号量集机制”,现在信号量机制已经被广泛的应用到单处理机和多处理机系统以及计算机网络中。

5.在IOS系统GCD的semaphore.h头文件中提供三个方法进行PV操作

在IOS系统GCD的semaphore.h头文件中提供三个方法进行PV操作
// 这value是初始化多少个信号量
1.dispatch_semaphore_create(long value); 
// 这个方法是P操作对信号量减一,dsema这个参数表示对哪个信号量进行减一,如果该信号量为0则等待,timeout这个参数则是传入等待的时长。
2.dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); 
// 这个方法是V操作对信号量加一,dsema这个参数表示对哪个信号量进行加一
3.dispatch_semaphore_signal(dispatch_semaphore_t dsema);

6.常见的信号量的应用场景

a.加锁(互斥)
b.异步返回
c.控制线程并发数

示例:利用信号量或同步锁对多线程操作iphoneNumber变量进行互斥

#import "ViewController.h"

@interface ViewController ()

/// iphone的数量
@property (nonatomic,assign) int iphoneNumber;
/// 互斥用的信号量
@property (nonatomic,strong) dispatch_semaphore_t semaphore;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.iphoneNumber = 1000;
    // 初始化1个信号量
    self.semaphore = dispatch_semaphore_create(1);
    
    /// 通过信号量进行互斥,开启三个窗口(线程)同时卖iphone
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
    thread1.name = @"窗口1";
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
    thread2.name = @"窗口2";
    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphone) object:nil];
    thread3.name = @"窗口3";
    
    /// 通过同步锁进行互斥,开启三个窗口(线程)同时卖iphone
//    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphoneWithSynchronization) object:nil];
//    thread1.name = @"窗口1";
//    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphoneWithSynchronization) object:nil];
//    thread2.name = @"窗口2";
//    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellIphoneWithSynchronization) object:nil];
//    thread3.name = @"窗口3";
    [thread1 start];
    [thread2 start];
    [thread3 start];
}

/// 通过信号量达到互斥
- (void)sellIphone
{
    while (1) {
        // P操作对信号量进行减一,然后信号量变0,限制其他窗口(线程)进入
        dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
        
        if (self.iphoneNumber > 0) // 检查还有没iphone可卖
        {
            NSLog(@"卖出iphone剩下%d台iphone",--self.iphoneNumber);
            
        }
        else
        {
            NSLog(@"iphone没有库存了");
            return;
        }
        
        // V操作对信号量进行加一,然后信号量为1,其他窗口(线程)就能进入了
        dispatch_semaphore_signal(self.semaphore);
    }
}

/// 通过同步锁进行互斥,通过同步锁会比通过信号量控制的方式多进入该临界代码(线程数量-1)次
- (void)sellIphoneWithSynchronization
{
    while (1) {
        
        @synchronized (self) {
            if (self.iphoneNumber > 0) // 检查还有没iphone可卖
            {
                NSLog(@"%@卖出iphone剩下%d台iphone",[NSThread currentThread].name,--self.iphoneNumber);
            }
            else
            {
                NSLog(@"iphone没有库存了");
                return;
            }

        }
    }
}


@end

示例2:

公交车上司机和售票员的配合问题。加锁(互斥)

1.司机需要等待售票员关门后才能开车
2.售票员需要等待司机停车后才能开门

// 司机是否停车的信号量,
    dispatch_semaphore_t semaphoreStopBused = dispatch_semaphore_create(1);
    // 售票员是否关门的信号量
    dispatch_semaphore_t semaphoreCloseDoored = dispatch_semaphore_create(0);
    // 拿到全局队列
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 司机的相关操作
    dispatch_async(quene, ^{
        while (1) {
            // 司机等待售票员关门,DISPATCH_TIME_FOREVER表示这个信号量如果是0就一直等待这个信号量
            dispatch_semaphore_wait(semaphoreCloseDoored, DISPATCH_TIME_FOREVER);
            NSLog(@"司机开车");
            NSLog(@"司机停车");
            // 司机已关门,停车的信号量加一
            dispatch_semaphore_signal(semaphoreStopBused);
        }
    });
    
    // 售票员的相关操作
    dispatch_async(quene, ^{
        while (1) {
            // 售票员等待司机停车
            dispatch_semaphore_wait(semaphoreStopBused, DISPATCH_TIME_FOREVER);
            NSLog(@"售票员开门");
            NSLog(@"售票员关门");
            // 售票员已经关门,关门的信号量加一
             dispatch_semaphore_signal(semaphoreCloseDoored);
            
        }
    });

示例3:

生产和销售的问题(第一种情况加锁(互斥))

/*
     生产和销售的线程同时操纵iphoneNumber变量为了保证数据的正确性,并且生产到5台iphone就不再生产了。
    
     */
    
    // iphone数量
    __block int iphoneNumber = 0;
    // 生产和销售的互斥
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    
    // 拿到全局队列
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 生产iphone
    dispatch_async(quene, ^{
        while (1) {
            // 生产和销售的互斥,等待信号量
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            if (iphoneNumber < 5) {
                NSLog(@"生产iphone,目前有%d台",++iphoneNumber);
            }
            dispatch_semaphore_signal(semaphore);
            
        }
    });
    
    // 销售iphone
    dispatch_async(quene, ^{
        while (1) {
            // 生产和销售的互斥,等待信号量
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            if (iphoneNumber > 0) {
                NSLog(@"卖掉一台iphone,目前有%d台",--iphoneNumber);
            }
            dispatch_semaphore_signal(semaphore);
            
        }
    });

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大王算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值