信号量是一个整型值,有初始计数值;可以接收通知信号和等待信号。当信号量收到通知信号时,计数+1;当信号量收到等待信号时,计数-1;如果信号量为0,线程会被阻塞,直到信号量大于0,才会继续下去。
直接上代码
dispatch_queue_t workConcurrentQueue = dispatch_queue_create("cccccccc", DISPATCH_QUEUE_CONCURRENT);
//定义一个信号量,初始化为10
dispatch_semaphore_t semaphore1 = dispatch_semaphore_create(3);
//同时执行100个任务
for (int i = 0; i < 100; i++)
{
//当前信号量-1
dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// dispatch_async(workConcurrentQueue, ^{
// NSLog(@"任务%d执行",i+1);
NSLog(@"%@",[NSThread currentThread]);
sleep(1);
//当前信号量+1
dispatch_semaphore_signal(semaphore1);
});
}
打印:
2019-02-26 18:38:42.912065+0800 练习[56654:3448246] <NSThread: 0x600000c79bc0>{number = 3, name = (null)}
2019-02-26 18:38:42.912073+0800 练习[56654:3448243] <NSThread: 0x600000c41080>{number = 5, name = (null)}
2019-02-26 18:38:42.912088+0800 练习[56654:3448244] <NSThread: 0x600000c4b1c0>{number = 4, name = (null)}
2019-02-26 18:38:43.914035+0800 练习[56654:3448244] 开始执行
2019-02-26 18:38:43.914035+0800 练习[56654:3448246] 开始执行
2019-02-26 18:38:43.914035+0800 练习[56654:3448243] 开始执行
2019-02-26 18:38:43.914436+0800 练习[56654:3448243] <NSThread: 0x600000c41080>{number = 5, name = (null)}
2019-02-26 18:38:43.914443+0800 练习[56654:3448244] <NSThread: 0x600000c4b1c0>{number = 4, name = (null)}
2019-02-26 18:38:43.914487+0800 练习[56654:3448246] <NSThread: 0x600000c79bc0>{number = 3, name = (null)}
2019-02-26 18:38:44.919246+0800 练习[56654:3448244] 开始执行
2019-02-26 18:38:44.919246+0800 练习[56654:3448243] 开始执行
2019-02-26 18:38:44.919246+0800 练习[56654:3448246] 开始执行
说明:从执行结果中可以看出,虽然将10个任务都异步加入了并发队列,但是信号量机制控制了最大线程并发数,始终是3个线程在执行任务。此外,这些任务也没有阻塞主线程。
网友评论