To achieve mutual exclusion for Ajax

Source: Internet
Author: User
Tags constant data structures mutex thread unique id


As Ajax paradigms get more and more widely used, browser pages can keep the front-end user interface active (and therefore asynchronous in Ajax) while requesting data from the back server. However, problems can arise when both activities access the shared JavaScript and DOM data structures at the same time. JavaScript does not provide a classic solution for this concurrency program problem. This article describes the author's new insights on mutual exclusion mechanisms, which can play a good role in JavaScript.



Why do we need mutual exclusion?



When multiple program logical threads access the same data at the same time, the problem arises. Programs generally assume that the data they interact with does not change during the interaction. The code that accesses these shared data structures is called a critical section, and a mechanism that allows only one program access at a time is called a mutex. In an AJAX application, this occurs when the code that asynchronously handles the response from the XMLHttpRequest simultaneously manipulates data that is being used by the user interface. This shared data may be the DOM of JavaScript and/or Web pages that are used to implement the MVC data model. If either of them makes an uncoordinated change to the shared data, the logic of both will be interrupted.



Perhaps you would say, "Wait, why haven't I encountered this kind of problem?" ”。 Unfortunately, this problem is synchronous-dependent (also called a race condition), so they don't always happen, or perhaps never happen. Their probabilities are based on a number of factors. Based on robustness, rich Internet applications should prevent this by ensuring that these problems do not occur.



Therefore, a mutex is required to ensure that only one critical section can be opened at a time, and the other cannot be opened until it is finished. In most mainstream computer languages and execution frameworks, mutual exclusion mechanisms (often several) are available, but JavaScript applied to the browser side does not provide this mutex. Although there are some classic mutex implementations that do not require specialized language or environment support, even this requires some elements that are missing from JavaScript and browsers, such as Internet Explorer. The classic algorithms described next can play a good role in these browsers and languages.



Bread Shop Algorithm



In several mutual exclusion algorithms in computer science literature, the so-called Lamport Bakery algorithm can be effectively used in multiple competing control threads, the communication between the threads of the algorithm can only be carried out in shared memory (i.e., no special mechanisms such as semaphores, set-and-test, etc.). The basic idea of the algorithm stems from the bakery, because the bakery needs to pick the number and wait for the call. Listing 1 shows the framework of the algorithm, derived from Wikipedia, which allows each thread to enter and leave the critical section without conflict.



Listing 1. Lamport Bakery algorithm pseudo code



//Declaration & Initial values of global variables
Enter, Number:array [1..N] of integer = {0};
// Logic used by each thread ...
//Where "(A, B) < (c, D)"
//means "(a < C) or ((a = = c) and (b < D))"
Thread (i) {
while (true {
Enter [i] = 1;
Number[i] = 1 + max (number[1],..., number[n]);
Enter [i] = 0;    
for (j=1. j<=n; ++j) {
while (Enter[j]!= 0) {
//wait until thread J receives its number

while ((number[j]!=0)
&& ((number[j],j) < (number[i],i)) {
//wait until threads wit   H smaller numbers
//or with the same number, but with higher
//priority, finish their work
}
}
//critical section ...
Number[i] = 0;
//non-critical section ...
}
}



As shown above, the algorithm assumes that each thread knows its own thread number (constant i) and the total number of threads currently active (constant N). In addition, it is assumed that there is a way to wait or hibernate, for example, to temporarily release the CPU to another thread. Unfortunately, JavaScript in Internet Explorer does not have this ability. However, if multiple pieces of code that actually run on the same thread behave as if they were running on separate virtual threads, the bakery algorithm will not break. Similarly, JavaScript has a mechanism for scheduling functions after a specified delay, so you can use the following methods to optimize the bakery algorithm.



Wallace variant



The main obstacle to implementing the Lamport bakery algorithm in JavaScript is the lack of a thread API. Cannot determine which thread is currently running and the number of threads currently active, nor can the CPU be freed to other threads, and new threads cannot be created to manage other threads. Therefore, it is not possible to verify how specific browser events (for example, click Buttons, available XML answers, and so on) are assigned to threads.



One way to overcome these obstacles is to use command design patterns. You can override the bakery algorithm in the class that is responsible for managing the command by putting all the logic that should go into the critical section and all the data needed to start the logic into the Command object. The mutex only calls the critical extents in the absence of other critical extents (encapsulated as separate command object methods) at execution time, as if they were running in different virtual threads. The settimeout () mechanism of JavaScript is used to release the CPU to other waiting command.



Assuming a simple base class for the command object (see the command in Listing 2), you can define a class (see the mutex in Listing 3) to implement the Wallace variant of the bakery algorithm. Note that although the base class object can be implemented in JavaScript in many ways (for simplicity, this is a simple way), as long as each command object has a unique ID, and the entire critical area is encapsulated in a separate method, Then any object pattern can use this method.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.