Home > Web Front-end > JS Tutorial > body text

Simple JavaScript mutex lock sharing_javascript skills

WBOY
Release: 2016-05-16 17:01:41
Original
1976 people have browsed it

Last year there were several projects that required the use of JavaScript mutex locks, so I wrote several similar ones. This is one of them:

Copy code The code is as follows:

//Published by Indream Luo
//Contact: indreamluo@qq.com
//Version: Chinese 1.0.0

!function ($) {
    window.indream = window.indream || {};
    $.indream = indream;

indream.async = {
                                                                                                                                                ) .push(action);
//If the lock is not used, the current action blocks the lock
if (!$.indream.async.lockStatus[lock] && action) {
$.indream .async.lockStatus[lock] = true;
if (arguments.length > 2) {
var args = 'arguments[2]';
for (var i = 3; i < arguments .length; i ) {
                    args = ', arguments[' i ']';
                                   args ')');
                                                                                                                                 },
                                                                                                                                            /lock: Lock number
                                                                                                                                  Then execute the waiting queue, otherwise unlock
if ($ .indream.async.waitings [lock] .Length) {
$ .indream.async.waitings [lock] [0] ();
} else {
                                                                                                                                     🎜> lockStatus: [ ],
          //
                                                                                                                                                                                                                                                                                   (lock, action) {
$.indream.async.waitings[code] = $.indream.async.waitings[code] || [];
$.indream.async.waitings[code].push (action);
},
          //
                                                                        : {
                                                                                             //Listen
//
listen: function (actionName , callback) {
var list = $.indream.async.action.callback.list;
list[actionName] = list[actionName] || [];
.push(callback );
},
                                                                        args) {
var list = $.indream.async.action.callback .list;
if (list[actionName] && list[actionName].length) {
for (var i in list[actionName]) {
indream.async.action.call(list[ actionName][i], args);
                                                                                                 //Existing callback list
//
list: []
          },
                                                                                                                                                                                                                       🎜> if (arguments.length > 1) {
var args = 'arguments[1]';
for (var i = 2; i < arguments.length; i ) {
                args = ', arguments[' i ']';
                                                                 action(); > }
}
}
}(window.jQuery);



The elements of a mutex are:

•Lock and unlock
•Waiting queue
•Execution method
Usage of the above lock:


Copy code


The code is as follows:

//Define the name of the lock

var lock = 'scrollTop()';

//Use lock$.indream.async.lock(lock, function () { var scrollTop = $(window).scrollTop(); var timer ; var fullTime = 100; for (timer = 0; timer <= fullTime; timer = 10) { setTimeout('$(window).scrollTop(' (scrollTop * (fullTime - timer ) / fullTime) ');', timer);
}
//Release lock
setTimeout('$.indream.async.releaseLock("' lock '");', fullTime);
});



A brief explanation about the implementation of this implementation.

-Spin lock or semaphore
JavaScript itself does not have a lock function, so all locks are implemented at a high level.

According to the single-thread principle of JavaScript, JS’s thread resources are very limited and it is very unsuitable to use spin locks, so we chose to use semaphores.

The implementation of the spin lock is roughly like this. Of course, do while is more useful:

Copy code

The code is as follows:

while(true) {

//do something ...

}

This will inevitably occupy the thread resources. Unfortunately, JS only has one thread for execution, so this is very unsuitable. Of course, if necessary, you can choose a combination of setInterval and clearInterval to implement it, and the effect will be good.

The semaphore method is used here, and the principle is simple, as short as the code. The execution order of the work is roughly:

• Push the code segment (callback action) into the waiting queue
• Determine whether the current lock is held, and if it is held, wait for release, otherwise acquire the lock and execute the callback
• When the lock is held Release, shift out the next callback in the waiting queue, pass the lock to it and execute

-Automatic release or manual release
The most comfortable way is of course to lock it and then automatically release it when the current program is executed. However, this is not easy because there are more situations that require customized release scenarios.

The method that uses locks is asynchronous, so various other asynchronous contents usually appear, such as AJAX and jQuery animation. At this time, automatic release does not meet the requirements, because in fact, the real "execution is completed" is after its internal asynchronous callback is completed, that is, basically only the developer can control it, so manual release is chosen here.

However, there is still a flaw, which is repeated release.

You can see that all lock objects are public, or it should be said that all JS objects are public, unless local variables are isolated at the access level. However, the "lock" itself here is a public resource, so there is no way to deal with it.

The optimization that can be done here should be like setInterval and clearInterval, locking with a public lock name and unlocking with a private lock ID to prevent repeated releases. However, it is not in the old code above, and it is estimated that it will be used soon.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!