Stijn Sanders
Stijn Sanders

Reputation: 36840

firefox addon: create a new thread and dispatch nsIRunnable to it?

Why does this crash FireFox? Copy and paste this code into the browser console (Ctrl+Shift+J):

function TestRunner(){}
TestRunner.prototype={
    classDescription:"TestRunner",
    classID:Components.ID("{09AA3487-7531-438D-B0B2-80BC24B584C0}"),
    contractID:"@yoy.be/TestRunner;1",
    QueryInterface:XPCOMUtils.generateQI([Components.interfaces.nsIRunnable]),
    run:function(){
        console.log("ping");
    }
};
Components.classes["@mozilla.org/thread-manager;1"].getService().newThread(0).dispatch(new TestRunner(),0);

Upvotes: 0

Views: 277

Answers (2)

nmaier
nmaier

Reputation: 33162

Starting with Firefox 4(-ish) the whole Javascript engine became far less thread safe, to the extend where e.g. simple things such as just "reading" a string concurrently may cause memory corruption (because these reads might actually materialize strings views for string ropes).

Therefore it was decided that dispatching javascript-implemented nsIRunnable isn't supported anymore as there is no safe way to use it, and people should switch over to ChromeWorkers where possible.

Edit You said in the comments that you wanted to implement nsIChannel/nsIProtocolHandler. AFAIK you can implement nsIProtocolHandler and nsIChannel without any threads and binaries. If you still have to have threads and/or binaries, then your Javascript XPCOM (stub) components would "simply" communicate with a ChromeWorker via message passing (pass around ArrayBuffers/typed arrays; those are zero-copy). The ChromeWorker would then do any heavy lifting, incl. any js-ctypes calls to interface with binaries.

Upvotes: 1

Neil
Neil

Reputation: 55382

You can run non-XPCOM JavaScript on other threads using (chrome) workers, and you can dispatch C++ implementations of nsIRunnable to other threads, but you can only use XPConnect on the main thread. This is because XPConnect objects could be cycle-collected and the cycle collector isn't threadsafe.

Upvotes: 0

Related Questions