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(); 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 /// Create a mutex (single cap semaphore)
Semaphore.Mutex = () => new Semaphore(1); Semaphore.mutex = () => new Semaphore(1);
const sem_example = async () => { const sem_example = async (locks) => {
let semaphore = Semaphore.Mutex(); let semaphore = new Semaphore(locks || 1); //Semaphore.Mutex();
return await Promise.all([ const gen_runner = (name, num, time) => {
semaphore.using(async () => { if(!time || time < 0) return semaphore.bind_using(() => {
for(let i=0;i<10;i++) { for(let i=0;i<num;i++) console.log(`${name}: ${i}`);
await new Promise(resolve => setTimeout(resolve, 100)); return num;
console.log(`first: ${i}`); });
} else return semaphore.bind_using(async () => {
return 10; for(let i=0;i<num;i++) {
}), await new Promise(resolve => setTimeout(resolve, time));
semaphore.using(async () => { console.log(`${name}: ${i}`);
for(let i=0;i<15;i++) {
await new Promise(resolve => setTimeout(resolve, 75));
console.log(`second: ${i}`);
} }
return 15; return num;
}), });
semaphore.using(() => { };
for(let i=0;i<500;i++) console.log(`third ${i}`);
return 500; return await Promise.all([
}), gen_runner("first", 10, 100)(),
gen_runner("second", 15, 75)(),
gen_runner("third", 500)(),
]); ]);
}; };

Loading…
Cancel
Save