happy-rusty
    Preparing search index...

    Function Mutex

    • Creates a new Mutex<T> protecting the given value.

      Type Parameters

      • T

        The type of the protected value.

      Parameters

      • value: T

        The initial value to protect.

      Returns Mutex<T>

      A new Mutex<T> instance.

      // Protect a simple value
      const counter = Mutex(0);

      // Protect an object
      const state = Mutex({ users: [], lastUpdate: Date.now() });

      // Protect a resource
      const db = Mutex(await createConnection());
      // Database transaction safety
      const connection = Mutex(db);

      async function transfer(from: string, to: string, amount: number) {
      await connection.withLock(async (conn) => {
      await conn.beginTransaction();
      try {
      const balance = await conn.query('SELECT balance FROM accounts WHERE id = ?', [from]);
      if (balance < amount) {
      throw new Error('Insufficient funds');
      }
      await conn.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, from]);
      await conn.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, to]);
      await conn.commit();
      } catch (e) {
      await conn.rollback();
      throw e;
      }
      });
      }
      // Token refresh with mutex
      const authState = Mutex({ token: '', expiresAt: 0 });

      async function getToken(): Promise<string> {
      return await authState.withLock(async (state) => {
      if (Date.now() > state.expiresAt) {
      const response = await fetch('/api/refresh');
      const data = await response.json();
      state.token = data.token;
      state.expiresAt = Date.now() + data.expiresIn * 1000;
      }
      return state.token;
      });
      }
      // File write serialization
      const fileLock = Mutex('/path/to/file.json');

      async function appendToFile(data: string) {
      await fileLock.withLock(async (path) => {
      const content = await fs.readFile(path, 'utf-8');
      const json = JSON.parse(content);
      json.entries.push(data);
      await fs.writeFile(path, JSON.stringify(json, null, 2));
      });
      }