JavaScript multithreaded Asynchronous queue

Source: Internet
Author: User

First of all, you need to know the general usage of jquery.deferred, then, let's get to the point:

Library code:

/*! * Multithreaded Asynchronous Queue * relies on jQuery 1.8+ (if you're using 1.6 or 1.7, just replace the then method in the source with the pipe method)*//** * @n {number} positive integer, thread count*/functionQueue (n) {n= parseint (n | | 1, 10); return(n && n > 0)?NewQueue.prototype.init (n):NULL;} Queue.prototype={init:function(n) { This. threads = [];  This. taskList = [];  while(n--) {             This. Threads.push (New  This. Thread)}},/** * @callback {fucntion} Promise object is done when the callback function, its return value must be a Promise object*/Push:function(callback) {if(typeofCallback!== ' function ')return; varindex = This. Indexofidle (); if(Index! =-1) {             This. Threads[index].idle (callback)Try{console.log (' thread-' + (index+1) + ' accept the task! ')}Catch(e) {}}Else {             This. Tasklist.push (callback);  for(vari = 0, L = This. threads.length; I < L; i++) {                (function(thread, self, id) {Thread.idle (function(){                        if(Self.taskList.length > 0) {                            Try{console.log (' thread-' + (id+1) + ' accept the task! ')}Catch(e) {}varPromise = Self.taskList.pop () ();//the correct return value should be a Promise object                            returnPromise.promise?promise:thread.promise; } Else {                            returnthread.promise})}) ( This. Threads[i], This, i); }}, Indexofidle:function () {        varThreads = This. threads, Thread=NULL, Index=-1;  for(vari = 0, L = threads.length; I < L; i++) {Thread=Threads[i]; if(thread.promise.state () = = = ' Resolved ') {Index=i;  Break; }        }        returnindex; }, Thread:function () {         This. Promise = $.        Deferred (). Resolve (). Promise ();  This. Idle =function(callback) { This. Promise = This. Promise.then (Callback)}}; Queue.prototype.init.prototype= Queue.prototype;

Examples of Use:

    varQueue =NewQueue (3); Create a queue with 3 threads
Task-1 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},8000); returndefer.promise ()})
Task-2 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},2000); returndefer.promise ()})
Task-3 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},6000); returndefer.promise ()})
Task-4 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},3000); returndefer.promise ()})
Task-5 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},2000); returndefer.promise ()})
Task-6 Queue.push (function(){ vardefer = $. Deferred (); SetTimeout (function() {defer.resolve ()},2000); returndefer.promise ()})

The console has a function (called a task) that shows Queue.push, which process is ultimately processed

After instantiation, all 3 threads in the queue are in an idle state.
assigning task-1 to Thread 1, this task takes 8s
assigning task-2 to Thread 2, this task takes 2s
assigning task-3 to Thread 3, this task takes 6s

Because there are currently no idle processes, the internal queue adds task-4, task-5, task-6 to the waiting area

Because task-2 takes 2s, process 2 is first liberated, then TASK-4 is assigned to process 2, and so on, the last console shows the process usage is: 1, 2, 3, 2, 2, 3

JavaScript multithreaded Asynchronous queue

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.