37 lines
700 B
Swift
37 lines
700 B
Swift
//
|
|
// AsyncSemaphore.swift
|
|
// MNNLLMiOS
|
|
//
|
|
// Created by 游薪渝(揽清) on 2025/8/27.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
public actor AsyncSemaphore {
|
|
private var value: Int
|
|
private var waiters: [CheckedContinuation<Void, Never>] = []
|
|
|
|
init(value: Int) {
|
|
self.value = value
|
|
}
|
|
|
|
func wait() async {
|
|
if value > 0 {
|
|
value -= 1
|
|
} else {
|
|
await withCheckedContinuation { continuation in
|
|
waiters.append(continuation)
|
|
}
|
|
}
|
|
}
|
|
|
|
func signal() {
|
|
if waiters.isEmpty {
|
|
value += 1
|
|
} else {
|
|
let waiter = waiters.removeFirst()
|
|
waiter.resume()
|
|
}
|
|
}
|
|
}
|