Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active April 5, 2022 19:32
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save DmitrySoshnikov/b75a2dbcdb60b18fd9f05b595135dc82 to your computer and use it in GitHub Desktop.
Agents example
// agent-smith.js
/**
* Receive shared array buffer in this worker.
*/
onmessage = (message) => {
// Worker's view of the shared data.
let heapArray = new Int32Array(message.data);
let indexToModify = 1;
heapArray[indexToModify] = 100;
// Send the index as a message back.
postMessage(indexToModify);
};
<!DOCTYPE html>
<html>
<head>
<title>Agents example</title>
</head>
<body>
<!--
NOTE: if you run this example locally, run it in Firefox,
since Chrome due to security reasons doesn't allow loading
web workers from a local file.
-->
<script type="text/javascript">
// Shared data between this agent, and another worker.
let sharedHeap = new SharedArrayBuffer(16);
// Our view of the data.
let heapArray = new Int32Array(sharedHeap);
// Create a new agent (worker).
let agentSmith = new Worker('agent-smith.js');
agentSmith.onmessage = (message) => {
// Agent sends the index of the data it modified.
let modifiedIndex = message.data;
// Check the data is modified:
console.log(heapArray[modifiedIndex]); // 100
};
// Send the shared data to the agent.
agentSmith.postMessage(sharedHeap);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment