import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let threadPool = ThreadPool(maxThread: 5)
for i in 0...10 {
threadPool.addTask {
print("Task\(i)")
}
}
threadPool.waitUntilAllTasksAreFinished()
print("Hello world")
threadPool.terminate()
threadPool.addTask {
print("Done")
}
}
}
class ThreadPool {
private var queue: DispatchQueue
private var threadPool: [Thread] = []
private var tasks: [() -> Void] = []
private var semaphore: DispatchSemaphore
private let lock = NSLock()
private var isTerminating = false
init(maxThread: Int) {
queue = DispatchQueue(label: "com.example.threadPool", attributes: .concurrent)
semaphore = DispatchSemaphore(value: maxThread)
for i in 0...maxThread {
let thread = Thread(target: self, selector: #selector(doTask), object: nil)
thread.start()
threadPool.append(thread)
}
}
func addTask(task: @escaping () -> Void) {
lock.lock()
defer{ lock.unlock() }
if !isTerminating {
tasks.append(task)
}
}
func waitUntilAllTasksAreFinished() {
queue.sync {
while(!tasks.isEmpty) {
}
}
}
func terminate() {
lock.lock()
isTerminating = true
tasks.removeAll()
lock.unlock()
for thread in threadPool {
thread.cancel()
}
}
@objc func doTask() {
while true {
semaphore.wait()
var task: (() -> Void)? = nil
lock.lock()
if !tasks.isEmpty {
task = tasks.removeFirst()
}
lock.unlock()
if let task = task {
task()
print("current signal: \(Thread.current)")
}
semaphore.signal()
}
}
}
Swift—手写线程池(附代码)
于 2024-05-12 20:10:44 首次发布