Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Created December 5, 2016 05:43
Show Gist options
  • Save hoodwink73/8964e62906ba042e29266e4a40cf9d9b to your computer and use it in GitHub Desktop.
Save hoodwink73/8964e62906ba042e29266e4a40cf9d9b to your computer and use it in GitHub Desktop.
Obligatory CSP examples
csp.go(function* () {
// this routine acts
// like the referee
var table = csp.chan();
// two routines represents two players
// they have access to the same channel
csp.go(player, ["ping", table])
csp.go(player, ["pong", table])
yield csp.put(table, {hits: 0});
// if a player fails to
// hits the ball after a second
// the referee will close the channel
// and the game will end
yield csp.timeout(1000)
table.close()
});
function* player(name, table) {
while (true) {
var ball = yield csp.take(table);
if (ball === csp.CLOSED) {
console.log(name + ": table's gone")
return;
}
ball.hits += 1
console.log(name + "" + ball.hits);
// who ever takes the ball, puts it back
// after 100ms for the other player to take
yield csp.timeout(100)
yield csp.put(table, ball)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment