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
的每次调用都等待一个承诺:
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;
}
相关文章