Friday, September 4th, 2009

Stratified JavaScript; Concurrency features in JavaScript

Category: JavaScript

Alex Fritze has introduced Stratified JavaScript, an experiment that allows us to play with some concurrency features in JavaScript in a cross browser way.

It features:

The ability to pause execution: hold()

javascript

  1. var elem = document.getElementById("animated_element");
  2.   var x = 0;
  3.   while (true) {
  4.     elem.style.left = x;
  5.     x = (x + 10) % 200;
  6.     hold(100);
  7.   }

Fork-Join Parallelism

javascript

  1. function animate(elemname, duration_ms, step_ms) {
  2.     var elem = document.getElementById(elemname);
  3.     var start_time = new Date();
  4.     var x = 0;
  5.     do {
  6.       elem.style.left = x;
  7.       x = (x + 10) % 200;
  8.       hold(step_ms);
  9.     } while (duration_ms > new Date() - start_time);
  10.   }
  11.  
  12.   function par(a, b) {
  13.     alert("all done");
  14.   }
  15.  
  16.   par(animate("animated_element_1", 10000, 100),
  17.       animate("animated_element_2", 7000, 80));

Exploratory parallelism

javascript

  1. animate("animated_element_1", 10000, 100) @
  2. animate("animated_element_2", 7000, 80);
  3.  
  4. alert("all done");

Suspend/Resume

javascript

  1. function waitForEvent(event, elem) {
  2.     suspend {
  3.       var rv;
  4.       var listener_func = function(e) {
  5.         rv = e;
  6.         resume();
  7.       };
  8.       elem.addEventListener(event, listener_func, false);
  9.     }
  10.     finally {
  11.       elem.removeEventListener(event, listener_func, false);
  12.     }
  13.     return rv;
  14. }

Under the hood, Stratified JavaScript is executed by a runtime based on Oni.

Kris Zyp asked for a comparison to Narrative JavaScript or JavaScript strands and Alex came back with:

The most important enhancement of SJS versus Narrative JavaScript or Strands is the support for ‘exploratory parallelism’ or ‘parallel selection’, as embodied by SJS’s Alt operator (‘@’). There are many problems that are tricky to express with just threads, but which can be expressed elegantly in a structured, compositional way with the use of Alt.

Posted by Dion Almaer at 6:11 am
1 Comment

++++-
4.4 rating from 45 votes

1 Comment »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.