Last active
October 22, 2019 22:06
-
-
Save danieljurek/4905b729456cb6d994df3ce479476418 to your computer and use it in GitHub Desktop.
This file contains 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
const { spawn, spawnSync } = require('child_process'); | |
const { promisify } = require('util'); | |
const { Semaphore } = require('await-semaphore'); | |
const spawnAsync = promisify(spawn); | |
async function go() { | |
console.log("===SYNC==="); | |
for (let i = 0; i < 10; i++) { | |
let result = spawnSync('node', ['sayhi.js', i], { shell: true }); | |
console.log(`${result.output}`); | |
} | |
console.log("===ASYNC==="); | |
let promises = [] | |
for (i = 0; i < 10; i++) { | |
let promise = new Promise((res, rej) => { | |
let childProcess = spawn('node', ['sayhi.js', i], { shell: true }); | |
let stdOut = ''; | |
let stdErr = ''; | |
childProcess.on('close', (code) => res({code, stdOut, stdErr})); | |
childProcess.stdout.on('data', (data) => stdOut = stdOut + data.toString()); | |
childProcess.stderr.on('data', (err) => stdErr = stdErr + data.toString()); | |
}); | |
promises.push(promise); | |
} | |
try { | |
console.log("awaiting parallel execution of", promises.length, "processes"); | |
const results = await Promise.all(promises); | |
console.log(results); | |
for (let item of results) { | |
console.log(item.stdOut); | |
} | |
} catch (ex) { | |
console.log("ERROR", ex); | |
} | |
console.log("WITH POOLING") | |
let commands = [] | |
for (i = 0; i < 10; i++) | |
{ | |
commands.push(['node', ['sayhi.js', i]]); | |
} | |
const semaphroe = new Semaphore(2); | |
poolPromises = []; | |
let liveCount = 0; | |
for (const command of commands) { | |
let promise = new Promise(async (res, rej) => { | |
console.log("LiveCount: ", liveCount); | |
let releaseSemaphore = await semaphroe.acquire(); | |
liveCount++; | |
console.log("LiveCount: ", liveCount); | |
let childProcess = spawn(command[0], command[1], { shell: true }); | |
let stdOut = ''; | |
let stdErr = ''; | |
childProcess.on('close', (code) => { | |
releaseSemaphore(); | |
console.log("LiveCount: ", liveCount); | |
liveCount--; | |
res({code, stdOut, stdErr}) | |
}); | |
childProcess.stdout.on('data', (data) => console.log(data.toString())); | |
childProcess.stderr.on('data', (err) => console.log(err.toString())); | |
console.log("LiveCount: ", liveCount); | |
}); | |
poolPromises.push(promise); | |
} | |
const poolPromiseResult = await Promise.all(poolPromises); | |
console.log(poolPromiseResult); | |
console.log("All done!"); | |
} | |
go(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment