examples/pool.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="../thread.js"></script>
<script>
// synchronous tasks
var arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
// use until 10 theads to distribute task load
var worker = thread().pool(10)
function runTask(id) {
worker.run(function (id) {
return this.arr.map(function(n) {
return Math.pow(id, n)
})
}, { arr: arr }, [ id ]).then(function(v) {
console.log(v)
})
}
for (var i = 0; i < 100; i += 1) { runTask(i) }
</script>
<script>
// asynchronous tasks
var results = []
var tasks = 100
// use until 10 theads to distribute task load
var worker2 = thread({ env: { x: 2 } }).pool(10)
function runAsyncTask(id) {
return function () {
worker2.run(function (num, done) {
return setTimeout(function () {
done(null, Math.round(env.x * num * Math.random() * 100))
}, Math.random() * 1000)
}, [ 2 ]).then(function (value) {
console.log('Result:', value)
results.push(value)
})
}
}
for (var x = 0; x < tasks; x += 1) {
setTimeout(runAsyncTask(i), Math.random() * 1000)
}
var intervalId = setInterval(function () {
if (results.length === tasks) {
clearInterval(intervalId)
console.log('Results:', results)
console.log('Used threads:', worker2.threadPool.length)
worker2.kill() // kill all threads
}
}, 250)
</script>
</body>
</html>