Blocking Channels

In notebook:
FrontEndMasters Async Javascript
Created at:
2016-09-22
Updated:
2016-09-22
Tags:
Fundamentals JavaScript
more complex example
  var ch = chan();

csp.go(function*(){
  while (true) {
    yield csp.put(ch,Math.random());
  }
});

csp.go(function*(){
  while (true) {
    yield csp.take( csp.timeout(500) );
    var num = yield csp.take(ch);
    console.log(num);
  }
});
Note: in a previous part of this workshop he talks about the ​while(true)​ pattern in generators. It works well in the case of a generator.Uses the CSP library. 

Every 500ms it pulls down a message. So the first generator can only push a new message every 500ms only.
To clarify: line #11: a new channel is created by the csp library, so this blocks the second generator function. Then, after 500ms, it's ready to take a message from the channel that the first process (line #5) is using.
Audience notices and Kyle agrees, that this particular library needs a global ​ch​ channel (state) to function. Not all libraries do though (like Kyle's).​csp.alts​ defines a list of channels, and acts on the first one the produces a message:
  csp.go(function*(){
  while(true) {
    var msg = yield csp.alts(ch1,ch2,ch3);
    console.log(msg);
  }
});
Shows the ping-pong example. 
One ​go​ routine for the "table" or "referee" and two other ​go​ routines as players. 
  csp.go(function* () {
  var table = csp.chan();
  
  csp.go(player, ['ping', table]);
  csp.go(player, ['pong', table]);
  
  yield csp.put(table, {hits: 0});
  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.hist += 1;
    console.log(name + " " + ball.hits);
    yield csp.timeout(100);
    yield csp.put(table, ball);
  }
}