let semaphore = DispatchSemaphore(value: 5) //允许的最大并发操作数
模拟执行有13个时长1s的任务,需要控制最多同一时间执行5个任务。使用倒计时记录任务完成情况
代码如下:
var timer: DispatchSourceTimer?
let semaphore = DispatchSemaphore(value: 5) //初始化信号量为1,允许的最大并发操作数
func threadBiggest() {
self.addTimerPrint()
//限制线程的最大并发数
let curQueue = DispatchQueue.global(qos: .background)
for i in 0..<13 {
curQueue.async {
self.semaphore.wait() //信号量-1
DispatchQueue.main.asyncAfter(deadline: .now()+1) {
print("并发执行",i)
self.semaphore.signal()
}
}
}
}
//添加倒计时测试
func addTimerPrint(){
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer?.schedule(deadline: .now(), repeating: .seconds(1))
var index: Int = 0
timer?.setEventHandler(handler: {
index += 1
print("倒计时--",index)
})
timer?.resume()
}
deinit {
if (timer != nil) {
timer?.cancel()
timer = nil
}
}
我们可以看到两个倒计时之间,最多只会执行5个任务
打印结果为:
image.png
通常我们开发过程中需要执行的任务,耗时时长是不确定的。接下来我们模拟有些耗时3s,有些耗时1s的任务。其他条件不变,替换curQueue.async中的内容为:
curQueue.async {
self.semaphore.wait() //信号量-1
if i%5 == 1 {
DispatchQueue.main.asyncAfter(deadline: .now()+1) {
print("并发执行",i)
self.semaphore.signal()
}
}else {
DispatchQueue.main.asyncAfter(deadline: .now()+3) {
print("并发执行",i)
self.semaphore.signal()
}
}
}
打印结果为:
image.png