Created
April 16, 2026 02:22
-
-
Save umair-khokhar/5f5473ef598020dc91a1872817e06534 to your computer and use it in GitHub Desktop.
ThreadPool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ThreadPool { | |
| #waiters = []; | |
| #jobs = []; | |
| constructor(threadCount, init, release) { | |
| this.abort = new AbortController(); | |
| for(let i = 0; i < threadCount; i++) { | |
| this.workers(init, release); | |
| } | |
| } | |
| async workers(init, release) { | |
| let shutdown = false; | |
| // FIX: used the correct AbortController API and used the class member abort | |
| this.abort.signal.addEventListener('abort', () => { | |
| shutdown = true; | |
| }); | |
| init(); | |
| while(!shutdown) { // FIX: I updated it from while(!shutdown && true) | |
| if(this.#jobs.length === 0) { | |
| await new Promise((resolve) => this.#waiters.push(resolve)) | |
| } | |
| const {job, resolve, reject} = this.#jobs.shift(); | |
| try { | |
| const response = await job(); | |
| resolve(response); | |
| } catch(err) { | |
| reject(err); | |
| } | |
| } | |
| release(); | |
| } | |
| enqueue(job) { | |
| const p = new Promise((resolve, reject) => { | |
| // FIX: Used the correct structure as Rueian suggested | |
| // Previously I mixed up this part. | |
| this.#jobs.push({job, resolve, reject}); | |
| }); | |
| if(this.#waiters.length > 0) { | |
| const wake = this.#waiters.shift() | |
| wake(); | |
| } | |
| return p; | |
| } | |
| shutdown() { | |
| this.abort.abort(); | |
| } | |
| // didn't get a chance for draining queue, killing waiters but could be done in cleanup function(s). | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment