Introduced in Hamsters.js Version 5.5.3,
a new optional parameter is introduced called sharedArray
, assuming your problem array is any one of JavaScript's Typed Arrays you can even see greater performance than prevously possible by telling the library to use
SharedArrayBuffers.
SharedArrayBuffers are used internally by Hamsters.js when passing sharedArray in your params object, these represent an advanced use case of the library and you cannot pass params.array and params.sharedArray at the same time, it's one or the other.
Now that we got that out of the way, it's important to understand there are differences between using Hamsters.js with params.array and params.sharedArray, here is a list of them below.
Now that you understand these basic rules,checkout the below example sourced from Hamsters.js Atomic Operations Example.
In the below method, we create a TypedArray and set sharedArray
in our params object to be that TypedArray, additionally we pass the dataType
param so the library knows what TypedArray we're using.
You'll notice we are no longer passing an output to rtn.data in this case, this is because we are making use of Atomic Operations, these allow us to modify our piece of data without having to manually move it around between threads which hurts performance,
check the link above to learn more about Atomics, this wiki is not a tutorial on atomic operations and will only cover the use of two operations. Load
and Store
, these methods ensure we load , modify, and write our data without interferring with another thread.
You'll also notice the use of params.index , this is a newly exposed internal use object. This tells you what elements the particular thread is going to be operating on, a start index and an end index. Make use of these to ensure you don't have two threads modifying the same array element.
Calculate Collatz Conjecture using Atomic Operations
const operator = function() {
var sharedArray = params.sharedArray; // Use shared array directly
var start = params.index.start || 0;
var end = params.index.end !== undefined ? params.index.end : sharedArray.length - 1;
for (var i = start; i <= end; i++) {
var x = Atomics.load(sharedArray, i); // Load the value atomically
var steps = 0;
while (x !== 1) {
if (x % 2 === 0) {
x = x / 2;
} else {
x = x * 3 + 1;
}
steps++;
}
Atomics.store(sharedArray, i, steps); // Store the result atomically
}
// No need to return anything, shared array is modified in place without race conditions thanks to precalculated index's
};
const params = {
sharedArray: new Int32Array([12323,2232,33232,42112,50209,665,712,823,9292,1001]),
dataType: 'Int32',
threads: 4
};
hamsters.run(params, operator, function(results) {
console.info(results);
}, function(error) {
console.error(error);
});
dataType
can be one of the below options.