Java中的Mutex--这看起来像是一个正确的实现吗? [英] Mutex in JavaScript - does this look like a correct implementation?

查看:29
本文介绍了Java中的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样式的锁保护吗?

推荐答案

您的实现允许与请求锁一样多的使用者获得锁;对lock的每次调用都等待一个承诺:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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;箭头函数关闭创建它们的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;
    };
}

现场示例:

数据-lang="js"数据-隐藏="真"数据-控制台="真"数据-巴贝尔="假">
"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;
}

这篇关于Java中的Mutex--这看起来像是一个正确的实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆