From 0a7984e64d1cb5189e21187db89ec9492a020326 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Mon, 11 Nov 2024 01:59:56 -0800 Subject: [PATCH] Move function and make it private. --- src/lib/pool.ts | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/lib/pool.ts b/src/lib/pool.ts index d98f7bc..fbdc10a 100644 --- a/src/lib/pool.ts +++ b/src/lib/pool.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2024 Chris Duncan // SPDX-License-Identifier: GPL-3.0-or-later +const Worker = globalThis.Worker type Task = { data: object, @@ -37,28 +38,30 @@ export class Pool { .map(() => { return new Thread(this.#url) }) } + #assign (thread: Thread, task: Task) { + thread.isAvailable = false + thread.worker.onmessage = (event) => { + console.log('work done') + if (this.#tasks.length > 0) { + const next = this.#tasks.shift() + this.#assign(thread, next) + } else { + thread.isAvailable = true + } + task.resolve(event.data) + } + console.log('posting') + thread.worker.postMessage(task.data) + } + async work (data: object): Promise { return new Promise(resolve => { const thread = this.#threads.find(t => t.isAvailable) if (thread) { - this.assign(thread, { data, resolve }) + this.#assign(thread, { data, resolve }) } else { this.#tasks.push({ data, resolve }) } }) } - - assign (thread: Thread, task: Task) { - thread.isAvailable = false - thread.worker.addEventListener('message', (event) => { - if (this.#tasks.length > 0) { - const task = this.#tasks.shift() - this.assign(thread, task.data) - } else { - thread.isAvailable = true - } - task.resolve(event.data) - }, { once: true }) - thread.worker.postMessage(task.data) - } } -- 2.34.1