Skip to content

Instantly share code, notes, and snippets.

@nmn
Last active August 29, 2015 14:18
Show Gist options
  • Save nmn/f9124e3e998297507111 to your computer and use it in GitHub Desktop.
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.
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