Javascript 在JS中正确实现互斥机制
我需要一些关于这方面的信息。搜索库,但似乎没有人完全异步执行。最接近的是异步互斥,但它是用与ES6不兼容的TypeScript编写的 我的框架草案是这样的Javascript 在JS中正确实现互斥机制,javascript,multithreading,mutex,Javascript,Multithreading,Mutex,我需要一些关于这方面的信息。搜索库,但似乎没有人完全异步执行。最接近的是异步互斥,但它是用与ES6不兼容的TypeScript编写的 我的框架草案是这样的 class Mutex { constructor() { this.promise = Promise.resolve(); } runExclusive(callback, ...args) { return (this.promise = this.promise.then(()
class Mutex {
constructor() {
this.promise = Promise.resolve();
}
runExclusive(callback, ...args) {
return (this.promise = this.promise.then(() => callback(...args)));
}
}
let mutex = new Mutex();
console.log('Thread A before mutex...');
mutex.runExclusive(function() {
console.log('Thread A acquired lock...');
for (let i = 0; i < 10**10; ++i) { }
console.log('Thread A releasing lock...');
}).then(function() {
console.log('Thread A after mutex...');
for (let i = 0; i < 10**9; ++i) { }
console.log('Thread A after mutex...');
});
console.log('Thread B before mutex...')
mutex.runExclusive(function() {
console.log('Thread B acquired lock...');
for (let i = 0; i < 10**8; ++i) { }
console.log('Thread B releasing lock...');
}).then(function() {
console.log('Thread B after mutex...');
for (let i = 0; i < 10**9; ++i) { }
console.log('Thread B after mutex...');
});
类互斥{
构造函数(){
this.promise=promise.resolve();
}
runExclusive(回调,…args){
return(this.promise=this.promise.then(()=>callback(…args));
}
}
设mutex=new mutex();
log('Thread A before mutex…');
mutex.runExclusive(函数(){
log('Thread A acquired lock…');
对于(设i=0;i<10**10;++i){
log('Thread A releasing lock…');
}).然后(函数(){
log('Thread A after mutex…');
对于(设i=0;i<10**9;++i){}
log('Thread A after mutex…');
});
log('互斥前的线程B…')
mutex.runExclusive(函数(){
log('Thread B acquired lock…');
对于(设i=0;i<10**8;++i){}
log('Thread B releasing lock…');
}).然后(函数(){
log('mutex之后的线程B…');
对于(设i=0;i<10**9;++i){}
log('mutex之后的线程B…');
});
问题是所有关键部分的跑步者都被链接成一个,在所有跑步者完成后同时解锁,等待最后一个跑步者
我得到这个输出
“在互斥对象之前执行线程…”“互斥之前的线程B…”
“线程已获取的锁…”
“穿过释放锁…”
“在互斥对象之后执行线程…”
“在互斥对象之后执行线程…”
“线程B已获取锁…”
“线程B释放锁…”
“互斥后的线程B…”
“互斥后的线程B…” 而正确的输出是 “在互斥对象之前执行线程…”
“互斥之前的线程B…”
“线程已获取的锁…”
“穿过释放锁…”
“线程B已获取锁…”
“在互斥对象之后执行线程…”
“线程B释放锁…”
“互斥后的线程B…”
“在互斥对象之后执行线程…”
“互斥后的线程B…”
谢谢你的想法。为什么在JS中没有真正的并发时使用互斥?“…但它是用TypeScript编写的,与ES6不兼容”-TypeScript被传输到JavaScript o.o