Caesar
Caesar

Reputation: 8514

Mutex in JavaScript - does this look like a correct implementation?

Not an entirely serious question, more of a shower thought: JavaScript's await keyword should allow for something that feels an awful lot like a mutex in your average "concurrent language".

function Mutex() {
    var self = this; // still unsure about how "this" is captured
    var mtx = new Promise(t => t()); // fulfilled promise ≡ unlocked mutex
    this.lock = async function() {
        await mtx;
        mtx = new Promise(t => {
            self.unlock = () => t();
        });
    }
}
// Lock
await mutex.lock();
// Unlock
mutex.unlock();

Is this a correct implementation (apart from proper error handling)? And… can I have C++-RAII-style lock guards?

Upvotes: 13

Views: 13997

Answers (3)

Jans Rautenbach
Jans Rautenbach

Reputation: 469

I recommend using a library like async-mutex:

const mutex = new Mutex();
// ...
const release = await mutex.acquire();
try {
    // ...
} finally {
    release();
}

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074475

Your implementation allows as many consumers obtain the lock as ask for it; each call to lock waits on a single promise:

function Mutex() {
    var self = this; // still unsure about how "this" is captured
    var mtx = new Promise(t => t()); // fulfilled promise ≡ unlocked mutex
    this.lock = async function() {
        await mtx;
        mtx = new Promise(t => {
            self.unlock = () => t();
        });
    }
}

const mutex = new Mutex();

(async () => {
  await Promise.resolve();
  await mutex.lock();
  console.log("A got the lock");
})();
(async () => {
  await Promise.resolve();
  await mutex.lock();
  console.log("B got the lock");
})();

You'd need to implement a queue of promises, creating a new one for each lock request.

Side notes:

  • new Promise(t => t()) can be more simply and idiomatically written Promise.resolve() :-)
  • No need for self if you're using arrow functions like that; arrow functions close over the this where they're created (exactly like closing over a variable)
  • Probably would make sense for unlock to be a resolution value of the lock promise, so only the code that obtained the lock can release it

Something like this:

function Mutex() {
    let current = Promise.resolve();
    this.lock = () => {
        let _resolve;
        const p = new Promise(resolve => {
            _resolve = () => resolve();
        });
        // Caller gets a promise that resolves when the current outstanding
        // lock resolves
        const rv = current.then(() => _resolve);
        // Don't allow the next request until the new promise is done
        current = p;
        // Return the new promise
        return rv;
    };
}

Live Example:

"use strict";
function Mutex() {
    let current = Promise.resolve();
    this.lock = () => {
        let _resolve;
        const p = new Promise(resolve => {
            _resolve = () => resolve();
        });
        // Caller gets a promise that resolves when the current outstanding
        // lock resolves
        const rv = current.then(() => _resolve);
        // Don't allow the next request until the new promise is done
        current = p;
        // Return the new promise
        return rv;
    };
}

const rand = max => Math.floor(Math.random() * max);

const delay = (ms, value) => new Promise(resolve => setTimeout(resolve, ms, value));

const mutex = new Mutex();

function go(name) {
    (async () => {
        console.log(name + " random initial delay");
        await delay(rand(50));
        console.log(name + " requesting lock");
        const unlock = await mutex.lock();
        console.log(name + " got lock");
        await delay(rand(1000));
        console.log(name + " releasing lock");
        unlock();
    })();
}
go("A");
go("B");
go("C");
go("D");
.as-console-wrapper {
  max-height: 100% !important;
}

Upvotes: 22

Bergi
Bergi

Reputation: 664579

Is this a correct implementation?

No. If two tasks (I can't say "threads") try to do mutex.lock() while it is currently locked, they will both get the lock at the same time. I doubt that's what you want.

A mutex in JS is really just a boolean flag - you check it, you set it when you acquire a lock, you clear it when you release the lock. There's no special handling of race conditions between checking and acquiring as you can do it synchronously in single-threaded JS, without any other threads interfering.

What you seem to be looking for however is a queue, i.e. something where you can schedule yourself to get the lock and will be notified (through a promise) when the previous lock is released.

I'd do that with

class Mutex {
    constructor() {
        this._lock = null;
    }
    isLocked() {
        return this._lock != null;
    }
    _acquire() {
        var release;
        const lock = this._lock = new Promise(resolve => {
            release = resolve;
        });
        return () => {
            if (this._lock == lock) this._lock = null;
            release();
        };
    }
    acquireSync() {
        if (this.isLocked()) throw new Error("still locked!");
        return this._acquire();
    }
    acquireQueued() {
        const q = Promise.resolve(this._lock).then(() => release);
        const release = this._acquire(); // reserves the lock already, but it doesn't count
        return q; // as acquired until the caller gets access to `release` through `q`
    }
}

Demo:

class Mutex {
    constructor() {
        this._lock = Promise.resolve();
    }
    _acquire() {
        var release;
        const lock = this._lock = new Promise(resolve => {
            release = resolve;
        });
        return release;
    }
    acquireQueued() {
        const q = this._lock.then(() => release);
        const release = this._acquire();
        return q;
    }
}
const delay = t => new Promise(resolve => setTimeout(resolve, t));

const mutex = new Mutex();

async function go(name) {
    await delay(Math.random() * 500);
    console.log(name + " requests lock");
    const release = await mutex.acquireQueued();
    console.log(name + " acquires lock");
    await delay(Math.random() * 1000);
    release()
    console.log(name + " releases lock");
}
go("A");
go("B");
go("C");
go("D");

Upvotes: 7

Related Questions