Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created July 25, 2011 08:18
Show Gist options
  • Save DmitrySoshnikov/1103751 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/1103751 to your computer and use it in GitHub Desktop.
Primitive Actor-processes
<html>
<head>
<title>Process</title>
<style type="text/css">
#p-0 {color: green;}
#p-1 {color: blue;}
.p {
float: left;
width: 300px;
border: 1px solid #CCC;
margin: 5px;
padding: 5px;
}
</style>
</head>
<body>
<div id="p-0" class="p"></div>
<div id="p-1" class="p"></div>
<script type="text/javascript" charset="utf-8">
/**
* Process constructor (implements Actor model)
* @param {Object} state - contains the process state,
* including `receiver` property - main receiving "loop"
*/
function Process(state) {
for (var k in state) {
this[k] = state[k];
}
this.activator = this.activator.bind(this);
this.pid = Process.pid++;
}
/**
* Sends a message to this Actor (process)
* asynchronously. Receive is scheduled
* by the host environment's (browser)
* setTimeout implementation, so really, the
* simplest and primitive version of processes.
*/
Process.prototype.send = function () {
this.message = arguments;
setTimeout(this.activator, 0);
};
/**
* Activates the receiver in context of the process
*/
Process.prototype.activator = function () {
this.receiver.apply(this, this.message);
};
Process.prototype.toString = function () {
return '#' + this.pid;
};
/**
* Process ids counter
*/
Process.pid = 0;
/**
* Helper wrapper to create a process
*/
function spawn(receiver) {
return new Process({receiver: receiver})
}
</script>
<script type="text/javascript">
var processes = [];
var value = 'ping';
var n = 0;
// Create two actor-processes with the same receiving "loop"
// Both send "ping" or "pong" message to each other
for (var k = 0; k < 2; k++) {
// receiver accepts a message in format [from, message]
// where from - is the process which sends the message
processes[k] = spawn(function ([from, message]) {
var formattedMessage = [
'Process <strong>', this,
'</strong> got <strong>"', message,
'"</strong> from process <strong>' + from,
'</strong>. N: ', n, '</br>'
].join('');
this.block.innerHTML += formattedMessage;
// continue up to 100 messages
if (n < 100) {
from.send([this, swapValue(value)]);
n++;
}
});
// each process can additionally have
// any other helper state properties
processes[k].block = document.getElementById('p-' + k);
}
function swapValue() {
return (value = value == 'ping' ? 'pong' : 'ping');
}
// p-1 starts the ping-pong game,
// sending "ping" to p0
processes[0].send([processes[1], value]);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment