Last active
August 29, 2015 14:18
-
-
Save nmn/f9124e3e998297507111 to your computer and use it in GitHub Desktop.
CSP - distribute expensive tasks to workers - A contrived example to show the strength and flexibility of CSP when compared to FRP.
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
import {go, chan, put, take, buffers, putAsync, CLOSED} from 'js-csp' | |
const BUFFER_LIMIT = 100 | |
const NUM_OF_WORKERS = 4 | |
var inputChannel = csp.chan(buffers.dropping(BUFFER_LIMIT)) | |
function fakeDataGenerator(){ | |
putAsync(Math.random()) | |
setTimeout(fakeDataGenerator, Math.random() * 2000) | |
} | |
fakeDataGenerator() | |
for(var i = 0; i < NUM_OF_WORKERS; i++){ | |
// imagine task.js takes a number and posts a response after an expensive computation. | |
let worker = new Worker('task.js'); | |
let workerResponse = chan() | |
worker.addEventListener('message', function(e) { | |
putAsync(workerResponse, e.data) | |
}, false); | |
go(function*(){ | |
while(true){ | |
var value = yield take(inputChannel) | |
if(value === CLOSED){ | |
workerResponse.close() | |
worker.terminate() | |
return; | |
} | |
worker.postMessage(value) | |
var response = yield take(workerResponse) | |
console.log(response) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment