Semaphore: Better example function. Changed `Semaphore.Mutex()` -> `Semaphore.mutex()` to avoid class naming convention confusion.

Fortune for async-timeout-js's current commit: Small blessing − 小吉
master
Avril 3 years ago
parent d54a5e8f51
commit b2070f1918
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -79,33 +79,34 @@ function Semaphore(cap)
self.release_raw();
}
};
/// Returns a lambda that, when executed, runs `using(func)` and returns the awaitable promise.
this.bind_using = (func) => { return () => self.using(func); };
}
/// Create a Mutex
Semaphore.Mutex = () => new Semaphore(1);
/// Create a mutex (single cap semaphore)
Semaphore.mutex = () => new Semaphore(1);
const sem_example = async () => {
let semaphore = Semaphore.Mutex();
const sem_example = async (locks) => {
let semaphore = new Semaphore(locks || 1); //Semaphore.Mutex();
return await Promise.all([
semaphore.using(async () => {
for(let i=0;i<10;i++) {
await new Promise(resolve => setTimeout(resolve, 100));
console.log(`first: ${i}`);
}
return 10;
}),
semaphore.using(async () => {
for(let i=0;i<15;i++) {
await new Promise(resolve => setTimeout(resolve, 75));
console.log(`second: ${i}`);
const gen_runner = (name, num, time) => {
if(!time || time < 0) return semaphore.bind_using(() => {
for(let i=0;i<num;i++) console.log(`${name}: ${i}`);
return num;
});
else return semaphore.bind_using(async () => {
for(let i=0;i<num;i++) {
await new Promise(resolve => setTimeout(resolve, time));
console.log(`${name}: ${i}`);
}
return 15;
}),
semaphore.using(() => {
for(let i=0;i<500;i++) console.log(`third ${i}`);
return 500;
}),
return num;
});
};
return await Promise.all([
gen_runner("first", 10, 100)(),
gen_runner("second", 15, 75)(),
gen_runner("third", 500)(),
]);
};

Loading…
Cancel
Save