| 22 | } |
| 23 | |
| 24 | function process(key: string) { |
| 25 | const lock = locks.get(key) |
| 26 | if (!lock || lock.writer || lock.readers > 0) return |
| 27 | |
| 28 | // Prioritize writers to prevent starvation |
| 29 | if (lock.waitingWriters.length > 0) { |
| 30 | const nextWriter = lock.waitingWriters.shift()! |
| 31 | nextWriter() |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | // Wake up all waiting readers |
| 36 | while (lock.waitingReaders.length > 0) { |
| 37 | const nextReader = lock.waitingReaders.shift()! |
| 38 | nextReader() |
| 39 | } |
| 40 | |
| 41 | // Clean up empty locks |
| 42 | if (lock.readers === 0 && !lock.writer && lock.waitingReaders.length === 0 && lock.waitingWriters.length === 0) { |
| 43 | locks.delete(key) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | export async function read(key: string): Promise<Disposable> { |
| 48 | const lock = get(key) |