Monday, June 05, 2006

Lightweight threads with Narrative Javascript

[ 2006-06-05: Updated the code to use 'concede' instead of 'yield' to prevent clashes with the new keyword in Javascript 1.7 ]

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.

Categories: ,

4 Comments:

Anonymous jag said...

"yield" was recently introduced as a new keyword in Mozilla's JS implementation (what will be v1.7), so this demo unfortunately fails in recent builds of SeaMonkey and Firefox.

It was introduced for Python-like generators. For details see Mozilla bug 326466, comment 39

8:05 PM  
Blogger Chris Double said...

Thanks for the heads up, I've updated the code to use 'concede' instead of 'yield'.

8:16 PM  
Blogger Chris Double said...

It looks like the generators in JS v1.7 could be used to build lightweight threads as well. Very nice!

8:25 PM  
Anonymous chocolateboy said...

Most cool.

11:31 AM  

Post a Comment

<< Home