Skip to main content
Module

x/async/mod.ts>RwLock

🦕 Asynchronous primitive modules for Deno.
Latest
class RwLock
import { RwLock } from "https://deno.land/x/async@v2.1.0/mod.ts";

A reader-writer lock implementation that allows multiple concurrent reads but only one write at a time. Readers can acquire the lock simultaneously as long as there are no writers holding the lock. Writers block all other readers and writers until the write operation completes.

import { AsyncValue } from "https://deno.land/x/async@v2.1.0/testutil.ts";
import { RwLock } from "https://deno.land/x/async@v2.1.0/rw_lock.ts";

const count = new RwLock(new AsyncValue(0));

// rlock should allow multiple readers at a time
await Promise.all([...Array(10)].map(() => {
  return count.rlock(async (count) => {
    console.log(await count.get());
  });
}));

// lock should allow only one writer at a time
await Promise.all([...Array(10)].map(() => {
  return count.lock(async (count) => {
    const v = await count.get();
    console.log(v);
    count.set(v + 1);
  });
}));

Constructors

new
RwLock(value: T)

Creates a new RwLock with the specified initial value.

Methods

lock<R>(f: (value: T) => R | PromiseLike<R>): Promise<R>

Acquires the lock for both reading and writing, and invokes the specified function with the current value of the lock. All other readers and writers will be blocked until the function completes.

rlock<R>(f: (value: T) => R | PromiseLike<R>): Promise<R>

Acquires the lock for reading, and invokes the specified function with the current value of the lock. Other readers can acquire the lock simultaneously, but any writers will be blocked until the function completes.