Simple JavaScript Mutex sharing

Source: Internet
Author: User
Tags eval mutex setinterval

  This article mainly introduces a simple JavaScript mutex related information, need friends can refer to the following

Last year there were several projects that needed to use JavaScript mutexes, so several similar ones were written, and this is 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: Lock number        //action: How to perform after unlocking        //      &N Bsp 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 (!$.indrea M.async.lockstatus[lock] && action) {                $.indream.async.lock Status[lock] = True                 if (Arguments.length > 2) {                    var args = ' arguments[2] ';                     for (var i = 3; i < arguments.length i++) {&nbs P                       args + = ', arguments[' + i + '];                                   & nbsp     eval (' $.indream.async.action.call (action, ' + args + ') ');                } else {                & nbsp   $.indream.async.action.call (action);                            }        },        //       //unlock &NBSp      //lock: Lock number        //        Releaselock:function (lock) {            $.indream.async.waitings[lock].shift ();           &NB Sp If the wait queue has an object, the wait queue is executed, otherwise the unlock             if ($.indream.async.waitings[lock].length) {  &N Bsp             $.indream.async.waitings[lock][0] ();            } else {                $.indream.async . lockstatus[lock] = false;                    },        //    &N Bsp  //Lock status        //        lockstatus: [],        //&N Bsp      /waiting event completion        //lock: Lock code, the same encoding will be integrated into a sequence, triggering the simultaneous triggering of the       of  //     &NBSp   Wait:function (lock, action) {            $.indream.async.waitings[code] = $.indrea M.async.waitings[code] | | [];             $.indream.async.waitings[code].push (action);        },        //       /wait sequence       &NBS P         waitings: [],        //       //data cache   &NBS P    //        action: {           //      & nbsp    //monitoring and callback related methods            //            Callback : {               //               //Supervisor Listen                //                Liste N:function (ActionName, callback) {                    var list = $.INDREAM.ASYNC.A Ction.callback.list;                     List[actionname] = List[actionname] | | [];                     List[actionname].push (callback);                },                //&nbs P              //callback                //  &N Bsp             call:function (actionname, args) {            &N Bsp       var list = $.indream.async.action.callback.list;                     if (List[actionname] && List[actionname].len Gth) {                       for (Var i in List[actionname]) {                  &NBS P         $.indream.async.action.call (List[actionname][i], args);                                   & nbsp        }                },         &NBSP ;      //               //Existing callback list         &NBS P      //                list: []         &NBSP ;  },            //           //Select the appropriate performer depending on whether the method exists and whether the parameter exists Style            //            Call:function (action) {              &NBSP if (action) {                    if (Arguments.length > 1) {                        var args = ' arguments[1] ';                         for (var i = 2; I < Arguments.lengt H i++) {                            args + = ', Argume nts[' + i + '] ';                                   & nbsp             eval (' action (' + args + ') ');                    } else {            & nbsp           action ();                                   & nbsp } &nbsP          }         {   }} (Window.jquery);       Several elements of a mutex are:   lock and unlock • Wait Queue • Execution method The usage of the above locks:     Copy code code as follows://define lock name var lock = ' ScrollTop ()'; Use lock $.indream.async.lock (lock, function () {    var scrolltop = $ (window). scrolltop ();     var time R     var fulltime = 100;     for (timer = 0 Timer <= fulltime Timer + +) {        settimeout (' $ (window). Scrol Ltop (' + (scrolltop * (Fulltime-timer)/fulltime) + '); ', timer;    }    //release lock     settimeout (' $.indream.async.releaselock ("' + lock + '); ', fulltime);} );     about the implementation of this, simply explained.    -Spin lock or semaphore JavaScript itself does not have a lock function, so the locks are made at the top level.   According to 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.   SPIN lock to achieve the appearance of the roughly like this, of course, do while more use:     Copy code code is as follows: while (true) {   //do something ...}   &N Bsp This necessarily requires a full thread of resources, but JS only aThread 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 the method of signal quantity is chosen, the principle is simple, just like the code is so short. The execution order of the work is roughly:   pushes the code snippet (the action of the callback) into the wait queue to determine if the current lock is held and waits to be freed if it is held, or to acquire the lock and perform a callback • When the lock is released, shift the next callback in the wait queue, pass the lock to it and execute    -Automatic release or manual release the most comfortable way to do this is, of course, locked and automatically released when the current program is finished, but it's not easy because there are more situations where you need to customize the release scenario.   itself uses locks in the asynchronous way, 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 is a defect, that is, repeated release.   can see all of the locks are publicly owned objects, or should say JS all objects are public, unless the local variable at the access level to quarantine. But here the "lock" itself is a public resource, so there is no way to deal with it.   can be done here, such as SetInterval and Clearinterval, with the public 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.