]> zoso.dev Git - libnemo.git/commitdiff
Move function and make it private.
authorChris Duncan <chris@zoso.dev>
Mon, 11 Nov 2024 09:59:56 +0000 (01:59 -0800)
committerChris Duncan <chris@zoso.dev>
Mon, 11 Nov 2024 09:59:56 +0000 (01:59 -0800)
src/lib/pool.ts

index d98f7bc87d8cf9d41bd3398be57b0c20619c6919..fbdc10a50baa1d1f3908804ff133d217e6df6187 100644 (file)
@@ -1,5 +1,6 @@
 // SPDX-FileCopyrightText: 2024 Chris Duncan <chris@zoso.dev>
 // 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<any> {
                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)
-       }
 }