Someone asked me if the "asynchronous" in AJAX means we should be worried about thread safety and global variables in client-side script. This is an interesting question to ponder.
I don't think we are in a position to even worry about concurrent threads in script. With no mechanism to control threads, we have to trust our browsers to "do the right thing". IE7 appears to use a single thread for executing script code in a page. Based on experiments with the native debugger and Winspector, the thread appears to be a message-pumping UI thread. I'd have to assume that other browsers (at least on Windows) also follow a single threaded model for simplicity. I have no proof, so any insight readers can provide would be appreciated.
In trying to confirm this behavior, I came across a 2003 post by Eric Lippert: "What are "threading models", and what threading model do the script engines use?". Here is a juicy excerpt:
* When the script engine is in a state where it cannot possibly call an ActiveX object -- for instance, if it has just been created and has not started running code, or if it is just about to be shut down -- then the script engine really is free threaded, but who cares? It can't do much in this state.
* When the script engine is initialized -- when the script engine host has started the process of passing code and object model state to the engine -- the script engine morphs into an apartment threaded object. All calls to the script engine must be on the initializing thread until the script engine is shut down again.
Eric then muddies the water in a later comment:
It's very difficult to do true multi-threading inside IE. However, there are clever things you can do with the setTimeout method. I've also been thinking that it might be interesting to describe setTimeout from a continuation-passing-style perspective.
It doesn't appear that Eric ever followed up on this comment, unfortunately.
But what about the A in AJAX? Assuming xmlHttp is a native object it is free to use any number of background threads to free up the browser's UI. When xmlHttp raises an event, however, that call must marshal to the thread responsible for executing script.
I do wonder what this single threaded model means for the future. As the amount of script code for AJAX and WPF/E grows, this model has the potential of being a bottleneck.