Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)
The Libuv Thread Pool.
In Simple Words: By default, Libuv maintains a thread pool of 4 worker threads for operations that the OS cannot handle asynchronously non-blockingly:
- File system operations (
fs.*). - DNS lookup operations (
dns.lookup). - Cryptographic functions (
crypto.pbkdf2,crypto.randomBytes,crypto.scrypt). - Compression (
zlib.*). Note: Network sockets (TCP/UDP, HTTP) do not use the thread pool; they use native non-blocking OS primitives (epollon Linux,kqueueon macOS).
javascript
const crypto = require('crypto');
// Measuring thread pool saturation (default 4 threads):
const start = Date.now();
for (let i = 0; i < 4; i++) {
crypto.pbkdf2('pass', 'salt', 100000, 512, 'sha512', () => {
console.log(`Hash ${i + 1} finished in ${Date.now() - start}ms`);
});
}