The contents of an Array sourced from a SharedArrayBuffer will consistently be comprised of zeroes

Regardless of my efforts, whenever I create an array from a buffer (no need for sharing), the resulting array contains elements equal to the length of the buffer, with all values being zero. It seems like the documentation on typed arrays in Mozilla doesn't apply to Chrome.

I am trying to obtain an array representation of a buffer that already holds data. My specific scenario involves a web worker receiving a shared array buffer with pre-existing data. But so far, I haven't been able to create a view representing that buffer.

function testIntBuffer(n) {
    return new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * n);
}

function fillIntBuffer(buffer, endInt) {
    for (var i = 0; i <= endInt; i++) {
        buffer[i] = i;
    }
    return buffer;
}

var a = testIntBuffer(10);
fillIntBuffer(a, 10);
console.log(a);

var b = new Int32Array(a);
console.log(b)

This is how the actual code in my project looks like (except for the fake data function):

//inside main.js
function fakeDataArray(n) {
    const arr = [];
    for(let i = 0; i <= n; i++) {
        arr[i] = Math.floor(Math.random() * 100);
    }
    return arr;
}

function normalArrayToSBA(rawData) {
    const n = rawData.length;
    const m = Int32Array.BYTES_PER_ELEMENT;
    const data = new SharedArrayBuffer(m * n);
    rawData.forEach((datum, i) => {
        data[i] = datum;
    });
    return [data, n, m];
}

function createWorker() {
        const w = new Worker('workerBundle.js');
        w.onmessage = (event) => {
            const command = event.data.command;
            if (command === 'workerFinish') {
                console.log('event recieved from worker: ', event);
            }
            if (!command) {
                return;
            }
        };
        return w;
    }

function startworker(dataInfo, options) {
    const worker = createWorker();
    function setWorkerData(dataInfo) {
        const priceBuffer = dataInfo[0];
        const size = dataInfo[1];
        const offset = dataInfo[2];
        worker.postMessage({
            command: 'setData',
            priceBuffer: priceBuffer,
            size: size,
            offset: offset
        });
    }
    function getWorkerStats(_options) {
        worker.postMessage({
            command: 'getStats',
            options: _options,
        });
    }
    const id = Math.random();
    setWorkerData(dataInfo);
    getWorkerStats(options);
}

let data = fakeDataArray(5751);
let dataInfo = normalArrayToSBA(data);
startworker(dataInfo);

//inside workerBundle.js

//eslint-disable-next-line no-unused-vars
const WorkerMessageInterface = {
    file: null,
    priceData: null,
    role: 'worker',
    id: null,
    pendingRequests: {},
    setRole(event) {
        WorkerMessageInterface.role = event.data.role;
        WorkerMessageInterface.id = event.data.id;
        self.postMessage({
            success: true,
            commandGiven: event.data.command
        });
    },
    //command: 'setFile'
    /*{ command: 'setFile', fileInfo: String }*/
    setFile(event) {
        WorkerMessageInterface.file = event.data.file;
        self.postMessage({
            success: true,
            commandGiven: event.data.command
        });
    },
    //command: 'setData'
    /**
     * @param {priceData} Array
     * @param {source} String - Indicates what utility mapping  is necesarry
     *                          to convert data into the highcharts format
    */
    setData(event) {
        const data = event.data;
        const priceBuffer = new Int32Array(data.priceBuffer);
        WorkerMessageInterface.priceData = [priceBuffer, data.size];
    },
    //command: 'getSignals'
    /**
     * @param {options} Object
    */
    getAverage(dataArray) {
        let sum = 0;
        let length = dataArray.length;
        dataArray.forEach((n) => {
            sum += n;
        });
        return sum / length;
    },
    getStats(event) {
        const ops = event.data.options;
        const id = WorkerMessageInterface.id;
        const data = WorkerMessageInterface.priceData;
        const stats = WorkerMessageInterface.getAverage(data);
        if (WorkerMessageInterface.role === 'worker') {
            self.postMessage({
                results: stats,
                command: 'workerFinish',
                id: id
            });
        }
    },
    listenForCommands() {
        self.onmessage = (event) => {
            const command = event.data.command;
            WorkerMessageInterface[command](event);
            self.postMessage({
                worker: true,
                commandGiven: command,
                status: 'recieved',
            });
        };
    }
};
WorkerMessageInterface.listenForCommands();

Answer №1

Ensure to pass the SharedArrayBuffer to the new Int32Array() function first, before executing the fillIntBuffer() method.

function initializeIntBuffer(n) {
  return new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * n);
}

function populateIntBuffer(buffer, endInt) {
  for (var i = 0; i <= endInt; i++) {
    buffer[i] = i;
  }
  return buffer;
}

var arrayA = initializeIntBuffer(10);
var arrayB = new Int32Array(arrayA);
populateIntBuffer(arrayB, 10);
console.log(arrayB);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods could I use to integrate multiple for loops within my code?

I have just begun learning python and am seeking guidance on creating an array with multiple for loops. ''' Postcondition: A 5x5 array displayed as follows: - - - - - - - - - - - - - - - - - - - - - - - - - ''' for row_index ...

Is it possible to await the response of a request in Socket.io with socket.on('answerToRequest')?

Can the following scenario work out? async function checkSocketStatus(){ socket.emit('checkOtherSocketStatus', otherSocketId); await socket.on('responseCheckSocketStatus', (status)=>{ console.log('status'); } ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed. Below is the code snippet: <template> <div class="custom-radio-button"> {{value}} <div v-for= "item in localValue"> <input type ...

What is the best way to create an associative array using jQuery and then send it through AJAX to be parsed by PHP?

Is there a way to create an associative array in jQuery and send it via ajax to a php page for processing? Here is an example of what I am trying to achieve... // jQuery if($something == true) { data[alt] = $(this).attr('alt'); data[sr ...

difficulty encountered when using the Angular delete method in conjunction with Express.js

I am trying to send a delete request to my Express server from Angular. remove: function (id) { return $http({ method: 'DELETE', url: '/users/delete/'+ id }) } In my Expr ...

Use the 'url' parameter to pass into the ajax function when using jQuery for online requests

I am working with an ajax code that retrieves data from an XML file locally. <script> function myFunction() { $("#dvContent").append("<ul></ul>"); $.ajax({ type: "GET", url: "test.xml", ...

Encountering an unfamiliar property in JSX dynamic component

I am attempting to display components after dynamically determining their name, but I keep encountering this issue: Unknown property ent on the <resultComponent> tag. Please remove this property from the element. The problematic code is located w ...

Different methods of displaying the next image from a URL without explicitly setting the dimensions

I am attempting to display an image in Next.js without specifying the width and height by using import Image from 'next/image';. It should be noted that the image is sourced from a URL, not a specific folder within the project. <Image si ...

The API version header has not been accurately transmitted

Hey there, I've run into a strange problem. Everything seems to work fine when I make API requests using postman or insomnia. However, when I try the same code on my website or even locally on localhost, the leads request doesn't go through and t ...

Collapse the sidebar using React when clicked

Just beginning to learn about React and I'm trying to figure out how to toggle the open/closed state of a react-pro-sidebar component using a click event: export default function MaterialLayout(props) { const { children } = props; const classes = us ...

Prevent the selection of Single Origin and House Blend options once the user opts for Espresso

<td> <select class="type"> <option value="Espresso">Espresso</option> <option value="" class="">Cappuccino</option> <opti ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional b ...

Contrast between using " and '

Similar Inquiry: When to Utilize Double or Single Quotes in JavaScript Comparison of single quotes and double quotes in JS As I delve into creating a Node.js Express web application, I've noticed that the tutorial consistently uses ' ins ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...

Progressive rendering of particles in THREE.js

I am new to the world of 3D and I'm trying to render particles as they are created. My goal is to have these 2000 particles render individually as they are created, but with the current code, they only render once all particles have been created. I h ...

The concept of asynchronicity and callbacks in JavaScript

As a newcomer to the world of JavaScript and Stack Overflow, I have been learning about synchronous, asynchronous, and callbacks through various videos and blogs. However, I still have a lingering doubt. If synchronous code means following a sequential ord ...

Is it possible to implement H-Screen in Tailwind without causing the page size to expand? My website has a fixed navbar at the top, and I

My setup includes PanelMaster, along with Panel 1 and Panel 2 components. PanelMaster: flex Panel1: flex-col Panel2: flex-col I have a Navbar component at the top of the page with 'h-1/5' applied to it. However, I'm facing an issue where ...