JavaScript中的互斥体-这看起来像是正确的实现吗?

时间:2018-06-28 15:31:34

标签: javascript mutex

这不是一个完全严肃的问题,更多的是在想一想:JavaScript的await关键字应该允许您感觉像普通的“并发语言”中的互斥体。

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();

这是否是正确的实现(除了适当的错误处理)?而且...我可以拥有C ++-RAII风格的锁卫吗?

2 个答案:

答案 0 :(得分:5)

您的实现允许尽可能多的消费者获得所需的锁;每个对lock的呼叫都等待一个诺言:

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");
})();

您需要实现一个诺言队列,为每个锁定请求创建一个新的诺言。

旁注:

  • new Promise(t => t())可以更简单和惯用地写成Promise.resolve():-)
  • 如果您使用的是箭头功能,则无需self;箭头函数 close over this的创建位置(就像在变量上封闭)
  • unlock用作锁定承诺的分辨率值可能很有意义,因此只有获得锁定的代码才能释放该锁定

类似这样的东西:

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;
    };
}

实时示例:

"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;
}

答案 1 :(得分:2)

  

这是正确的实现吗?

不。如果有两个任务(我不能说“线程”)在当前处于锁定状态时尝试执行mutex.lock(),则它们都将同时获得锁定。我怀疑那就是你想要的。

JS中的互斥锁实际上只是一个布尔标志-您对其进行检查,在获取锁时进行设置,在释放锁时将其清除。在检查和获取之间没有对竞争条件的特殊处理,因为您可以在单线程JS中同步进行此操作,而不会干扰任何其他线程。

然而,您似乎正在寻找的是 queue ,即您可以安排自己的时间来获取锁定,并且在释放先前的锁定时会(通过承诺)得到通知。 / p>

我愿意这样做

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`
    }
}

演示:

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");