Bluish Coder

Programming Languages, Martials Arts and Computers. The Weblog of Chris Double.


2006-06-05

More concurrency in Narrative Javascript

I've added to my lightweight threading example in Narrative Javascript to include support for sending and receiving messages between processes. The style of communication is based on the Erlang style of concurrency whereby processes communicate by sending messages. The threads2 example is here.

This page has two processes running on it. They start when the page loads. Both processes block immediately waiting for a message. When the message is received the append the text of the message to a textarea on the page:

function t1() {
  while(true) {
    var msg = receive->();
    var dest = document.getElementById("p2");
    dest.value += (msg +"\n");
  }
}

The 'receive' call blocks immediately if there are no messages in the processes mailbox. If a message arrives it unblocks and continues. It must be called as an asynchronous operation using the '->' operator for this to work. Processes are started using 'spawn':

var process1 = spawn(t1);
var process2 = spawn(t2);

Messages can be sent from one process to another using 'send'. This is also an asynchroous operation and must use the '->' operator. Here's the code that is run when a button is pressed:

function send1() {
  spawn(function() {
    var msg = document.getElementById('msg1').value;
    send->(process1, msg);
  });
}

It spawns a process which obtains the text from the text input area and sends it to one of the processes. This will cause that process to unblock and continue from the 'receive' call.

The updated code is:

Some ideas for things that would be nice to add or build upon:

  • Provide the equivalent of Termite's '!?' operator to allow sending a message and waiting for a reply to that message.
  • Use a persistent connection (ie. Comet) to an Erlang server and allow messages to be sent back and forth from Erlang processes and Narrative Javascript processes.
  • Add futures and promises allowing dataflow style programming.

Note that this code is just 'playing around' code and is not intended to be robust or production ready. I'm just exploring how these ideas that have traditionally been used on the server work in a client side browser based language.

Tags


This site is accessable over tor as hidden service 6vp5u25g4izec5c37wv52skvecikld6kysvsivnl6sdg6q7wy25lixad.onion, or Freenet using key:
USK@1ORdIvjL2H1bZblJcP8hu2LjjKtVB-rVzp8mLty~5N4,8hL85otZBbq0geDsSKkBK4sKESL2SrNVecFZz9NxGVQ,AQACAAE/bluishcoder/-61/


Tags

Archives
Links