Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the infinite loop created by setImmediate() in threads example #564

Merged
merged 2 commits into from
Mar 30, 2021
Merged

Fix the infinite loop created by setImmediate() in threads example #564

merged 2 commits into from
Mar 30, 2021

Conversation

m4heshd
Copy link
Contributor

@m4heshd m4heshd commented Feb 19, 2021

This is an update to the master.js used in worker threads example.

Issue:

The if condition that checks for pending jobs wrapped in the poll() function creates an infinite loop by calling itself using setImmediate(poll) when the job queue is empty. This creates a massive unnecessary workload for one or many cores in the CPU. (Comment in #237 )

function poll() {
    if (queue.length) {
        // If there's a job in the queue, send it to the worker
        job = queue.shift();
        worker.postMessage(job.message);
    } else {
        // Otherwise, check again later
        timer = setImmediate(poll); <- Gets looped infinitely if the queue has no jobs
    }
}

Fix:

Get rid of the setImmediate(poll) completely and introduce a function that schedules new jobs manually whenever asyncQuery() is called. Workers will remain idle rest of the time.

@JoshuaWise JoshuaWise merged commit 5493d14 into WiseLibs:master Mar 30, 2021
@JoshuaWise
Copy link
Member

Thanks for improving this 👍

@m4heshd
Copy link
Contributor Author

m4heshd commented Mar 30, 2021

@JoshuaWise My pleasure and much thanks to you for creating this flawless tool. Using this feature with better-sqlite3 heavily right now. Hoping to contribute more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants