小工具-任务线程组

/// 任务线程组 class TaskThreadGroup { /// 队列类型 enum QueueType { case concurrent(maxThreads: Int = -1) case serial } /// 主线串行任务组 var serialMainGroup: DispatchGroup /// 主线串行队列 var serialMainQueue: DispatchQueue /// 主线串行工作任务信号量 var serialMainSemaphore: DispatchSemaphore? /// 工作任务组 var group: DispatchGroup /// 工作队列 var queue: DispatchQueue /// 工作队列标签 var queueLabel: String { return self.queue.label } /// 工作任务信号量 var semaphore: DispatchSemaphore /// 最大并发线程 var maxThreads: Int = -1 /// 是否被取消 var isCancelled: Bool = false { didSet { print("已取消: \(self.queueLabel)") } } /// 工作队列名称 private var type: QueueType /// 工作队列类型 private var name: String /// 时间 private var time: Double /// 任务计数 private var count: Int = 0 /// 构建函数 /// - Parameter type: 任务线程组类型 init(type: QueueType, name: String? = nil) { self.group = DispatchGroup() self.serialMainGroup = DispatchGroup() self.serialMainQueue = DispatchQueue(label: "YGSerialQueue.main.\(String(Date().timeIntervalSince1970).md5())", qos: .utility) self.semaphore = DispatchSemaphore(value: 0) self.type = type self.name = name ?? (String(Date().timeIntervalSince1970).md5()) self.time = Date().timeIntervalSince1970 switch type { case .concurrent(maxThreads: let maxThreads): if maxThreads != -1 { self.maxThreads = maxThreads self.serialMainSemaphore = DispatchSemaphore(value: maxThreads) } self.queue = DispatchQueue(label: "并发线程-\(self.name)", qos: .utility, attributes: DispatchQueue.Attributes.concurrent) case .serial: self.queue = DispatchQueue(label: "串行线程-\(self.name)", qos: .utility) } print("创建: \(self.queueLabel)") } /// 添加任务 /// - Parameter task: 任务 /// - Returns: 无 func addTask(_ task: @escaping (DispatchSemaphore)->()) { if !self.isCancelled { self.count += 1 self.serialMainGroup.enter() self.serialMainQueue.async(group: self.serialMainGroup) { [count] in self.serialMainSemaphore?.wait() self.queue.async(group: self.group) { if !self.isCancelled { task(self.semaphore) self.semaphore.wait() } self.serialMainSemaphore?.signal() self.serialMainGroup.leave() } } } } func clearCount() { self.count = 0 } /// 任务组完成回调 /// - Parameters: /// - completion: 完成回调 /// - Returns: 无 func finish(completion: @escaping (()->())) { self.serialMainGroup.notify(queue: DispatchQueue.main) { // 全部调用完成后回到主线程,更新UI print("结束: \(self.queueLabel) 耗时: \(String(format: "%.3f", (Date().timeIntervalSince1970 - self.time) * 1000))ms 共\(self.count)个任务") completion() } } static var uploadTaskGroup: TaskThreadGroup = TaskThreadGroup(type: .concurrent(maxThreads: 3), name: "uploadTaskGroup") static var downloadTaskGroup: TaskThreadGroup = TaskThreadGroup(type: .concurrent(maxThreads: 10), name: "downloadTaskGroup") static var imageDownSamplingTaskGroup: TaskThreadGroup = TaskThreadGroup(type: .concurrent(maxThreads: 5), name: "imageDownSamplingTaskGroup") }