DOMWorkerThreads

From MozillaWiki
Revision as of 22:52, 13 August 2008 by Sicking (talk | contribs)
Jump to navigation Jump to search

Web Worker API Proposal

API Proposal

interface Worker
{
  void postMessage(in DOMString aMessage);

  // event handler attributes
           attribute EventListener onmessage;
           attribute EventListener onerror;
           attribute EventListener onload;
           attribute EventListener onunload;
};

[NoInterfaceObject] interface WorkerGlobalScope
{
  readonly attribute WorkerGlobalScope self;
  readonly attribute WorkerLocation location;
  readonly attribute boolean closing;
  void close();

  void postMessage(in DOMString aMessage);

  // event handler attributes
           attribute EventListener onmessage;
           attribute EventListener onunload;

  // WorkerUtils
  void importScripts([Variadic] in DOMString urls);
  readonly attribute Storage localStorage;
  Database openDatabase(in DOMString name, in DOMString version, in DOMString displayName, in unsigned long estimatedSize);
  void showNotification(in DOMString title, in DOMString subtitle, in DOMString description);
  void showNotification(in DOMString title, in DOMString subtitle, in DOMString description, in VoidCallback onclick);
};

[NoInterfaceObject] interface WorkerFactory {
  Worker createWorker(in DOMString scriptURL);
};

[NoInterfaceObject] interface WorkerLocation {
  readonly attribute DOMString href;
  readonly attribute DOMString protocol;
  readonly attribute DOMString host;
  readonly attribute DOMString hostname;
  readonly attribute DOMString port;
  readonly attribute DOMString pathname;
  readonly attribute DOMString search;
  readonly attribute DOMString hash;
};

Sample usage

Main page:

worker = createWorker("f.js");
worker.onmessage = function(e) {
  alert("The 100th Fibonacci number is " + e.data);
}
worker.postMessage(100);

f.js:

onmessage = function(e) {
  if (e.data <= 1)
    postMessage(e.data);

  w1 = createWorker("f.js");
  w1.onmessage = handler;
  w1.postMessage(e.data - 1);
  
  w2 = createWorker("f.js");
  w2.onmessage = handler;
  w2.postMessage(e.data - 2);
}

c = 0;
sum = 0;

function handler(e) {
  sum += parseInt(e.data);
  if (++c == 2) {
    postMessage(sum);
  }
}

References

The only thing I've seen so far is the Google Gears WorkerPool API. We would certainly like to provide a API that would make migrating Gears code trivial.