The type of the protected value.
The initial value to protect.
A new RwLock<T> instance.
// Basic usage
const counter = RwLock(0);
// Read (multiple can proceed)
const value = await counter.withRead(v => v);
// Write (exclusive)
await counter.withWrite(v => v + 1);
// Cache with read-heavy workload
const cache = RwLock(new Map<string, Data>());
// Many concurrent reads
async function get(key: string): Promise<Data | undefined> {
return cache.withRead(map => map.get(key));
}
// Occasional writes
async function set(key: string, value: Data): Promise<void> {
await cache.withWrite(map => { map.set(key, value); });
}
// Configuration that's read frequently, updated rarely
interface AppConfig {
apiUrl: string;
timeout: number;
features: string[];
}
const config = RwLock<AppConfig>({
apiUrl: 'https://api.example.com',
timeout: 5000,
features: ['feature-a', 'feature-b'],
});
// Read config (concurrent)
async function isFeatureEnabled(feature: string): Promise<boolean> {
return config.withRead(cfg => cfg.features.includes(feature));
}
// Update config (exclusive)
async function enableFeature(feature: string): Promise<void> {
await config.withWrite(cfg => {
if (!cfg.features.includes(feature)) {
cfg.features.push(feature);
}
});
}
Creates a new
RwLock<T>protecting the given value.