Simple JavaScript mutex sharing _javascript tips

Source: Internet
Author: User
Tags mutex

Last year there were several projects that needed to use JavaScript mutexes, so there were several similar ones, and this was one of them:

Copy Code code as follows:

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

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

Indream.async = {
//
Lock
Lock: Number of Locks
Action: Method to execute after unlocking
//
Lock:function (lock, action) {
$.indream.async.waitings[lock] = $.indream.async.waitings[lock] | | [];
$.indream.async.waitings[lock].push (action);
If the lock is not in use, 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 + '] ';
}
Eval (' $.indream.async.action.call (action, ' + args + ') ');
} else {
$.indream.async.action.call (action);
}
}
},
//
Unlock
Lock: Number of Locks
//
Releaselock:function (lock) {
$.indream.async.waitings[lock].shift ();
If the wait queue has an object, the wait queue is executed, otherwise the unlock
if ($.indream.async.waitings[lock].length) {
$.indream.async.waitings[lock][0] ();
} else {
$.indream.async.lockstatus[lock] = false;
}
},
//
Status of the lock
//
Lockstatus: [],
//
Wait for the event to complete
Lock: Locking code, the same encoding will be integrated into a sequence, triggered at the same time trigger
//
Wait:function (lock, action) {
$.indream.async.waitings[code] = $.indream.async.waitings[code] | | [];
$.indream.async.waitings[code].push (action);
},
//
Wait sequence
//
Waitings: [],
//
Data caching
//
Action: {
//
Methods of monitoring and callback
//
Callback: {
//
Listening
//
Listen:function (ActionName, callback) {
var list = $.indream.async.action.callback.list;
List[actionname] = List[actionname] | | [];
List[actionname].push (callback);
},
//
Callback
//
Call:function (ActionName, 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);
}
}
},
//
List of existing callbacks
//
List: []
},
//
Choose an appropriate way to perform depending on whether the method exists and whether the parameter exists
//
Call:function (Action) {
if (action) {
if (Arguments.length > 1) {
var args = ' arguments[1] ';
for (var i = 2; i < arguments.length; i++) {
args + = ', arguments[' + i + '] ';
}
Eval (' Action (' + args + ') ');
} else {
Action ();
}
}
}
}
}
} (Window.jquery);

Several elements of a mutex are:

• Lock and unlock
• Waiting queues
• Methods of implementation
Usage of the above locks:

Copy Code code as follows:

Define the name of the lock
var lock = ' scrolltop () ';
Using locks
$.indream.async.lock (lock, function () {
var scrolltop = $ (window). scrolltop ();
var timer;
var fulltime = 100;
for (timer = 0; timer <= fulltime + + 10) {
SetTimeout (' $ (window). scrolltop (' + (scrolltop * (Fulltime-timer)/fulltime) + '); ', Timer ';
}
Release lock
SetTimeout (' $.indream.async.releaselock (' + lock + '); ', fulltime);
});

About the implementation of this, simply explained.

-Spin lock or signal volume
JavaScript itself does not have the function of locking, so the locks are implemented at the top level.

Based on the JavaScript single-threaded principle, JS thread resources are very limited, very unsuitable for the use of spin locks, so choose the use of signal volume.

The spin lock is generally the way it is done, but of course the do is more used:

Copy Code code as follows:

while (true) {
Do something ...
}

This necessarily requires a full thread of resources, unfortunately JS only one thread can be used to execute, so this is very inapplicable. Of course, there is a need to choose the combination of setinterval and clearinterval to achieve, the effect will be good.

Here is the way to use the signal, the principle is simple, as the code is so short. The execution order of the work is roughly:

• Push the code snippet (action of the callback) into the wait queue
• Determine if the current lock is held and wait to be released if held, otherwise acquire the lock and execute the callback
• When the lock is freed, shift the next callback in the wait queue, pass the lock to it, and execute

-Automatically release or manually release
The most comfortable way to look is, of course, to lock it up and release it automatically when the current program is done, but that's not easy because there are more situations where you need to customize the release scenario.

The use of locks itself is the method in the asynchronous, so various other asynchronous content, such as Ajax and jquery animations, are usually present. This time, the automatic release is not in line with the requirements, because the actual "execution" is in its internal asynchronous callback completed, that is, basically only the developers themselves can grasp, so here is the choice of hand release.

However, there are still defects, that is, repeated release.

You can see all the lock objects are public, or you should say JS all objects are public, unless the local variable is isolated at the access level. But here the "lock" itself is a public resource, so there is no way to deal with it.

This can be done in the same way as SetInterval and clearinterval, with a common lock name for the lock, with a private lock ID to unlock, you can prevent the recurrence of the release. But not in the old code, which is expected to be used soon.

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.