Last active
April 5, 2022 19:32
-
-
Save DmitrySoshnikov/b75a2dbcdb60b18fd9f05b595135dc82 to your computer and use it in GitHub Desktop.
Agents example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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