Bluish Coder

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


2006-06-20

Lightweight threads with Narrative Javascript

I've put together a very simple lightweight threads example with Narrative Javascript. The demo creates two threads:

function t1() {
  var element = document.getElementById("one");
  var count = 0;
  while(true) {
    sleep->(100);
    element.innerHTML=count++;    
    concede->();
  }
}

function t2() {
  var element = document.getElementById("two");
  var count = 100;
  while(true) {
    sleep->(100);
    element.innerHTML=count--;    
    concede->();
  }
}

They set the text of an element on the page to the result of an incrementing or decrementing counter. It then sleeps for approximately 100 milliseconds. These are wrapped inside a process object and a scheduler started:

function start_demo() {
  var t = [];
  t[0] = new Process(t1);
  t[1] = new Process(t2);
  start(t);
  start_scheduler();
}

This start_demo is called when a button is pressed on the page and the threads start running. 'setTimeout' is used for the threads to give up timeslices back to the browser and to prevent the 'too much recursion' error that can otherwise occur.

The demo page is here. Source code to the scheduler is in schedule.njs and for the thread1 demo in thread1.njs.

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