1
- import { Mutex } from "./mutex .ts" ;
1
+ import { RawSemaphore } from "./_raw_semaphore .ts" ;
2
2
3
3
/**
4
4
* A reader-writer lock implementation that allows multiple concurrent reads but only one write at a time.
@@ -29,8 +29,8 @@ import { Mutex } from "./mutex.ts";
29
29
* ```
30
30
*/
31
31
export class RwLock < T > {
32
- #read = new Mutex ( ) ;
33
- #write = new Mutex ( ) ;
32
+ #read = new RawSemaphore ( 1 ) ;
33
+ #write = new RawSemaphore ( 1 ) ;
34
34
#value: T ;
35
35
36
36
/**
@@ -50,16 +50,16 @@ export class RwLock<T> {
50
50
* @returns A promise that resolves to the return value of the specified function.
51
51
*/
52
52
async lock < R > ( fn : ( value : T ) => R | PromiseLike < R > ) : Promise < R > {
53
- const wlock = await this . #write. acquire ( ) ;
53
+ await this . #write. acquire ( ) ;
54
54
try {
55
- const rlock = await this . #read. acquire ( ) ;
55
+ await this . #read. acquire ( ) ;
56
56
try {
57
57
return await fn ( this . #value) ;
58
58
} finally {
59
- rlock [ Symbol . dispose ] ( ) ;
59
+ this . #read . release ( ) ;
60
60
}
61
61
} finally {
62
- wlock [ Symbol . dispose ] ( ) ;
62
+ this . #write . release ( ) ;
63
63
}
64
64
}
65
65
@@ -71,19 +71,19 @@ export class RwLock<T> {
71
71
* @returns A promise that resolves to the return value of the specified function.
72
72
*/
73
73
async rlock < R > ( fn : ( value : T ) => R | PromiseLike < R > ) : Promise < R > {
74
- const wlock = this . #write. locked
75
- ? await this . #write. acquire ( )
76
- : { [ Symbol . dispose ] : ( ) => { } } ;
74
+ if ( this . #write. locked ) {
75
+ await this . #write. acquire ( ) ;
76
+ }
77
77
try {
78
78
// Acquire the read lock without waiting to allow multiple readers to access the lock.
79
- const rlock = this . #read. acquire ( ) ;
79
+ this . #read. acquire ( ) ;
80
80
try {
81
81
return await fn ( this . #value) ;
82
82
} finally {
83
- rlock [ Symbol . dispose ] ( ) ;
83
+ this . #read . release ( ) ;
84
84
}
85
85
} finally {
86
- wlock [ Symbol . dispose ] ( ) ;
86
+ this . #write . release ( ) ;
87
87
}
88
88
}
89
89
}
0 commit comments