信号量与并发控制
Posted 壮志凌云的博客园
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了信号量与并发控制相关的知识,希望对你有一定的参考价值。
代码1 - 未使用信号量控制并发:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (NSUInteger i = 0; i < 10; ++i) { NSLog(@"Task - 1"); } }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (NSUInteger i = 0; i < 10; ++i) { NSLog(@"Task - 2"); } }); } @end
输出:
Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2 Task - 1 Task - 2
代码 - 使用信号量控制并发:
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) dispatch_semaphore_t semaphore; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.semaphore = dispatch_semaphore_create(1); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER); for (NSUInteger i = 0; i < 10; ++i) { NSLog(@"Task - 1"); } dispatch_semaphore_signal(self.semaphore); }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER); for (NSUInteger i = 0; i < 10; ++i) { NSLog(@"Task - 2"); } dispatch_semaphore_signal(self.semaphore); }); } @end
输出:
Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 1 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2 Task - 2
以上是关于信号量与并发控制的主要内容,如果未能解决你的问题,请参考以下文章
linux驱动程序中的并发控制-5(信号量(semaphore))-47
linux驱动程序中的并发控制-5(信号量(semaphore))-47
全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段