iOS开发知识

IOS信号量(PV操作)

2017-05-22  本文已影响167人  一曰就是一天

本文为转载资料,原文地址: http://www.jianshu.com/p/02821f9d7777

一、信号量的简单介绍:

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(longvalue);// 这个方法是P操作对信号量减一,dsema这个参数表示对哪个信号量进行减一,如果该信号量为0则等待,timeout这个参数则是传入等待的时长。2.dispatch_semaphore_wait(dispatch_semaphore_tdsema,dispatch_time_ttimeout);// 这个方法是V操作对信号量加一,dsema这个参数表示对哪个信号量进行加一3.dispatch_semaphore_signal(dispatch_semaphore_tdsema);

二、下面是最简单的例子,利用信号量或同步锁对多线程操作iphoneNumber变量进行互斥。

////  ViewController.m//  semaphoreTest2////  Created by huangxianchao on 17/05/2017.//  Copyright © 2017 黄先超. All rights reserved.//#import"ViewController.h"@interfaceViewController()/// iphone的数量@property(nonatomic,assign)intiphoneNumber;/// 互斥用的信号量@property(nonatomic,strong) dispatch_semaphore_t semaphore;@end@implementationViewController- (void)viewDidLoad {    [superviewDidLoad];self.iphoneNumber =1000;// 初始化1个信号量self.semaphore = dispatch_semaphore_create(1);/// 通过信号量进行互斥,开启三个窗口(线程)同时卖iphoneNSThread*thread1 = [[NSThreadalloc] initWithTarget:selfselector:@selector(sellIphone) object:nil];    thread1.name =@"窗口1";NSThread*thread2 = [[NSThreadalloc] initWithTarget:selfselector:@selector(sellIphone) object:nil];    thread2.name =@"窗口2";NSThread*thread3 = [[NSThreadalloc] initWithTarget:selfselector:@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",[NSThreadcurrentThread].name,--self.iphoneNumber);            }else{NSLog(@"iphone没有库存了");return;            }        }    }}@end

注意:如果不理解可以注释信号量代码或者同步锁代码仔细观察iphoneNumber值的变化

三、控制同一个信号量(临界资源)下的相关线程最大的并发数

////  ViewController.m//  samephoreTest3////  Created by huangxianchao on 17/05/2017.//  Copyright © 2017 黄先超. All rights reserved.//#import"ViewController.h"@interfaceViewController()@end@implementationViewController- (void)viewDidLoad {    [superviewDidLoad];//这里的value控制基于semaphore这个信号量的相关线程最多几个线程并发运行dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);dispatch_queue_tquene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);//线程1dispatch_async(quene, ^{        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);NSLog(@"thread1 start");        dispatch_semaphore_signal(semaphore);NSLog(@"thread1 finish");    });//线程2dispatch_async(quene, ^{        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);NSLog(@"thread2 start");        dispatch_semaphore_signal(semaphore);NSLog(@"thread2 finish");    });//线程3dispatch_async(quene, ^{        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);NSLog(@"thread3 start");        dispatch_semaphore_signal(semaphore);NSLog(@"thread3 finish");    });}@end

下面是两个现实生活的例子

一、这是关于公交车上司机和售票员的配合问题。

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

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

// 司机是否停车的信号量,dispatch_semaphore_t semaphoreStopBused = dispatch_semaphore_create(1);// 售票员是否关门的信号量dispatch_semaphore_t semaphoreCloseDoored = dispatch_semaphore_create(0);// 拿到全局队列dispatch_queue_tquene = 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);        }    });

注意:

1.semaphoreStopBused和semaphoreCloseDoored信号量只能同时有一个是1,这值表示当前是停车了还是关门了,会触发相关的流程

2.让semaphoreCloseDoored为1,semaphoreStopBused为0试试,观察最开始的流程走的顺序有什么不同

二、生产和销售的问题

/*

生产和销售的线程同时操纵iphoneNumber变量为了保证数据的正确性,并且生产到5台iphone就不再生产了。

*/// iphone数量__blockintiphoneNumber =0;// 生产和销售的互斥dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);// 拿到全局队列dispatch_queue_tquene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);// 生产iphonedispatch_async(quene, ^{while(1) {// 生产和销售的互斥,等待信号量dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);if(iphoneNumber <5) {NSLog(@"生产iphone,目前有%d台",++iphoneNumber);            }            dispatch_semaphore_signal(semaphore);        }    });// 销售iphonedispatch_async(quene, ^{while(1) {// 生产和销售的互斥,等待信号量dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);if(iphoneNumber >0) {NSLog(@"卖掉一台iphone,目前有%d台",--iphoneNumber);            }            dispatch_semaphore_signal(semaphore);        }    });

22702FAC-1779-4C57-86A1-73C7E74A1121.png

上面图的结果是正确的,生产和销售后的数据都能对的上。

如果把代码更改为下面的情况,就是不用信号量去做互斥的话,看下图生成的错误结果图

/*

生产和销售的互斥保证得到的数据是正确的,并且生产到5台iphone就不再生产了

*/// iphone数量__blockintiphoneNumber =0;// 生产和销售的互斥//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);// 拿到全局队列dispatch_queue_tquene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);// 生产iphonedispatch_async(quene, ^{while(1) {// 生产和销售的互斥,等待信号量//            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);if(iphoneNumber <5) {NSLog(@"生产iphone,目前有%d台",++iphoneNumber);            }//            dispatch_semaphore_signal(semaphore);}    });// 销售iphonedispatch_async(quene, ^{while(1) {// 生产和销售的互斥,等待信号量//            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);if(iphoneNumber >0) {NSLog(@"卖掉一台iphone,目前有%d台",--iphoneNumber);            }//            dispatch_semaphore_signal(semaphore);}    });

看下图生成的错误结果图

图片.png

上图的结果有两处错误

1.连续生产两次iphone后产品的数量都是5。

2.连续卖掉两次iphone后产品的数量都是4。

参考资料:

http://baike.baidu.com/link?url=xfbl90QNrVjVE1oqELnAEYYvwI86XG_FLz-QEp9y4kn3icGzRXDwiPi4ICZ2FNhff8ho8MghcQyA0OaBRZKGMDKfUAsipmyooTWNyfdngjYkQ_krzsD_7KaSH_4PFv7y

上一篇下一篇

猜你喜欢

热点阅读