-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.swift
More file actions
41 lines (33 loc) · 815 Bytes
/
ThreadPool.swift
File metadata and controls
41 lines (33 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// ThreadPool.swift
//
//
// Created by Mihail Boyko on 01/04/24.
//
import Foundation
class ThreadPool {
private let queue: DispatchQueue
private let semaphore: DispatchSemaphore
init(workerCount: Int) {
queue = DispatchQueue(label: "com.threadpool.queue", attributes: .concurrent)
semaphore = DispatchSemaphore(value: workerCount)
}
func submit(task: @escaping () -> Void) {
semaphore.wait()
queue.async {
task()
self.semaphore.signal()
}
}
}
let threadPool = ThreadPool(workerCount: 3)
func sampleTask(id: Int) {
print("Task \(id) started")
Thread.sleep(forTimeInterval: 2) // Simulate work
print("Task \(id) finished")
}
for i in 1...10 {
threadPool.submit {
sampleTask(id: i)
}
}