Hamsters.js makes use of parameter based execution, the params object is a main component of using the library. Remember behind the scenes thread communication takes place using a message passing interface (MPI), we must send everything we want accessible within the context of a thread.
Using an example of a simple loop, let's walk through making this function use Hamsters
<!-- Uses main JavaScript thread --!>
function() {
var array = [0,1,2,3,4,5,6,7,8,9];
var results = new Array(array.length);
array.forEach(function(item) {
results.push((item * 120)/10);
});
console.log(results);
}
Now we can put this task onto its own thread like so
<!-- Does not use main javascript thread --!>
<!-- Uses one hamster thread --!>
<!-- No need to aggregate, data is never split --!>
function() {
var params = {
array:[0,1,2,3,4,5,6,7,8,9],
threads: 1
};
hamsters.run(params, function() {
var arr = params.array;
arr.forEach(function(item) {
rtn.data.push((item * 120)/10);
});
}, function(results) {
console.log(results);
});
}
Alternatively we can split this task among 2 threads for parallel execution like so
<!-- Does not use main JavaScript thread --!>
<!-- Uses two hamster threads --!>
<!-- Aggregates our individual thread results into one final output --!>
function() {
var params = {
array: [0,1,2,3,4,5,6,7,8,9],
threads: 2
};
hamsters.run(params, function() {
var arr = params.array;
arr.forEach(function(item) {
rtn.data.push((item * 120)/10);
});
}, function(results) {
console.log(results);
});
}
We can even define a function to split across all available threads like so
<!-- Does not use main JavaScript thread --!>
<!-- Uses all available hamster threads --!>
<!-- Aggregates our individual thread results into one final output --!>
function() {
var params = {
array: [0,1,2,3,4,5,6,7,8,9],
threads: hamsters.maxThreads
};
hamsters.run(params, function() {
var arr = params.array;
arr.forEach(function(item) {
rtn.data.push((item * 120)/10);
});
}, function(results) {
console.log(results);
});
}