空雲 Blog

Eye catchJavaScript/TypeScriptのforEach内の非同期処理をセマフォで同期させる

publication: 2023/07/23
update:2023/07/23

セマフォの必要性

Node.jsで非同期の通信プログラムを作るような場合、最大並列数を指定して実行したいことがあります。最大並列数が必要な理由としては、実行ごとに同期を取る順次処理だと速度が遅くなってしまい、かといって全てを並列にするとDoS攻撃状態になってしまうからです。

ということで、簡単にセマフォを実現できるライブラリを作りました。

@node-libraries/semaphore

semaphore()でインスタンスを作成し、acquire()でロック、release()でロック解除、all()で全てのロックが解除されるまで待ちます。

並列数1の場合

いか、並列数1で実行するサンプルです。セマフォで同期させているので、forEachでも非同期関数の順次処理が行われます。時々、forEachでは非同期が使えないという間違った情報が流れることがありますが、なんの問題もなく使えます。

import { semaphore } from "@node-libraries/semaphore"; const f = (value: string) => new Promise<void>((resolve) => { console.timeLog("debug", value); setTimeout(resolve, 1000); }); const main = async () => { console.time("debug"); const s = semaphore(); ["A", "B", "C", "D", "E"].forEach(async (v) => { await s.acquire(); await f(v); s.release(); }); await s.all(); // Wait for everything to be finished. console.timeLog("debug", "end"); }; main(); /* Result debug: 0.197ms A debug: 1.014s B debug: 2.027s C debug: 3.039s D debug: 4.040s E debug: 5.050s end */

並列数2の場合

semaphore(2)で並列数を2にしたサンプルです。AB,CD,Eという組み合わせて、同じようなタイミングで実行されているのが確認できます。

import { semaphore } from "@node-libraries/semaphore"; const f = (value: string) => new Promise<void>((resolve) => { console.timeLog("debug", value); setTimeout(resolve, 1000); }); const main = async () => { console.time("debug"); const s = semaphore(2); ["A", "B", "C", "D", "E"].forEach(async (v) => { await s.acquire(); await f(v); s.release(); }); await s.all(); // Wait for everything to be finished. console.timeLog("debug", "end"); }; main(); /* Result debug: 0.19ms A debug: 1.826ms B debug: 1.005s C debug: 1.005s D debug: 2.012s E debug: 3.028s end */

ライブラリのコード

コード量はこれだけです。ちなみにセマフォを実現するのにsetInterval系で並列インスタンスのチェックを定期的に行っているようなライブラリがありますが、そんな書き方をしなくてもカウント制御は普通にできるので、タイマー分だけ冗長になるだけです。

export const semaphore = ( limit = 1, count = 0, rs = new Array<() => void>(), all?: () => void ) => ({ acquire: () => ++count > limit && new Promise<void>((resolve) => rs.push(resolve)), release: () => (--count ? rs.shift()?.() : all?.()), all: () => count && new Promise<void>((resolve) => (all = resolve)), });

まとめ

Node.jsの非同期はシングルスレッドなので、実際のところは似非セマフォです。