信号量(dispatch_semaphore)

在我们平常开发中的一些基本概念与基本使用,dispatch_semaphore俗称信号量,也称为信号锁,在多线程编程中主要用于控制多线程下访问资源的数量,比如系统有两个资源可以使用,但同时有三个线程要访问,所以只能允许两个线程访问,第三个应当等待资源被释放后再访问,这时我们就可以使用dispatch_semaphore

第一、基本用法

#define  ZED_LOCK(lock)  dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);

#define  ZED_UNLOCK(lock)  dispatch_semaphore_signal(lock);

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event

{

//创建共享资源

 self.dict = [NSMutableDictionary dictionary];

 //初始化信号量(信号量为多少、就决定有多少条线程可以同时访问)*

 self.lock = dispatch_semaphore_create(1);

 for(int i =0; i <10; i++) {

        NSLog(@"异步添加任务:%d",i);

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

 *//信号量减1操作*

           ZED_LOCK(self.lock);

            [NSThread sleepForTimeInterval:3];

[**self**.dictsetObject:@"semaphore"forKey:@"key"];

            NSLog(@"i:%d --- thread:%@ --- 共享资源处理完成",i,[NSThread currentThread]);

 //信号量加1操作

            ZED_UNLOCK(self.lock);

        });

    }

}

2019-07-10 16:24:04.624906+0800 信号量[1162:240296] 异步添加任务:0

2019-07-10 16:24:04.625327+0800 信号量[1162:240296] 异步添加任务:1

2019-07-10 16:24:04.625452+0800 信号量[1162:240296] 异步添加任务:2

2019-07-10 16:24:04.625563+0800 信号量[1162:240296] 异步添加任务:3

2019-07-10 16:24:04.625680+0800 信号量[1162:240296] 异步添加任务:4

2019-07-10 16:24:04.625816+0800 信号量[1162:240296] 异步添加任务:5

2019-07-10 16:24:04.625935+0800 信号量[1162:240296] 异步添加任务:6

2019-07-10 16:24:04.626057+0800 信号量[1162:240296] 异步添加任务:7

2019-07-10 16:24:04.626598+0800 信号量[1162:240296] 异步添加任务:8

2019-07-10 16:24:04.627012+0800 信号量[1162:240296] 异步添加任务:9

2019-07-10 16:24:07.626102+0800 信号量[1162:240376] i:0 --- thread:{number = 3, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:10.629048+0800 信号量[1162:247192] i:1 --- thread:{number = 4, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:13.629891+0800 信号量[1162:247193] i:2 --- thread:{number = 5, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:16.630768+0800 信号量[1162:247196] i:3 --- thread:{number = 6, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:19.634851+0800 信号量[1162:247197] i:4 --- thread:{number = 7, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:22.639558+0800 信号量[1162:247198] i:5 --- thread:{number = 8, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:25.645110+0800 信号量[1162:247199] i:6 --- thread:{number = 9, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:28.650299+0800 信号量[1162:247200] i:7 --- thread:{number = 10, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:31.655295+0800 信号量[1162:247201] i:8 --- thread:{number = 11, name = (null)} --- 共享资源处理完成

2019-07-10 16:24:34.655921+0800 信号量[1162:247202] i:9 --- thread:{number = 12, name = (null)} --- 共享资源处理完成

第二、信号量奔溃案例

image

崩溃

image

崩溃

image

不崩溃

参考资料:https://www.cnblogs.com/yajunLi/p/6274282.html

参考资料:https://www.jianshu.com/p/7981e3357fe9

你可能感兴趣的:(信号量(dispatch_semaphore))