]> zoso.dev Git - libnemo.git/commitdiff
Fix pool incorrectly dividing up jobs and falling short of distributing all data...
authorChris Duncan <chris@zoso.dev>
Mon, 16 Dec 2024 21:05:17 +0000 (13:05 -0800)
committerChris Duncan <chris@zoso.dev>
Mon, 16 Dec 2024 21:05:17 +0000 (13:05 -0800)
src/lib/pool.ts

index 5211d2a38ca8c03a8ae7fd2043a36b0f690169ee..9c014ea6b30a00a353cdff9c54a63b000f4936c9 100644 (file)
@@ -21,11 +21,26 @@ type Thread = {
 * Processes an array of tasks using Web Workers.
 */
 export class Pool {
-       static #threads: Thread[] = []
        static #cores: number = Math.max(1, navigator.hardwareConcurrency - 1)
        static #queue: Job[] = []
+       static #threads: Thread[] = []
        static #url: string = URL.createObjectURL(new Blob([Workers], { type: 'text/javascript' }))
 
+       static get threadsBusy (): number {
+               let n = 0
+               for (const thread of this.#threads) {
+                       n += +(thread.job != null)
+               }
+               return n
+       }
+       static get threadsIdle (): number {
+               let n = 0
+               for (const thread of this.#threads) {
+                       n += +(thread.job == null)
+               }
+               return n
+       }
+
        static {
                for (let i = this.#cores; i > 0; i--) {
                        const thread = {
@@ -48,7 +63,7 @@ export class Pool {
                                thread.worker.postMessage({ name: job.name, buffer: job.data }, [job.data])
                        }
                } else {
-                       const chunk: number = 1 + (job.data.length / this.#cores)
+                       const chunk: number = 1 + (job.data.length / this.threadsIdle)
                        const next = job.data.slice(0, chunk)
                        job.data = job.data.slice(chunk)
                        if (job.data.length === 0) this.#queue.shift()