JS协程模拟并发

用Javascript协程去模拟并发。

"use strict"

let TICKET_NUM = 0;
let TICKET_TOTAL = 0;

let sale = function*(name){
    const saleName = name;
    while (true) {
        if ( TICKET_NUM <= 0 ) {
            console.log(`${saleName} => No ticket`);
            return;
        }else {
            TICKET_TOTAL++;
            console.log(`${saleName} => sales the No.${TICKET_TOTAL} ticket`);
            TICKET_NUM--;
        }
        yield;
    }
}

let thread = async()=>{
   
    let pool = [sale("A"), sale("B"), sale("C")];
    let len = pool.length;
    let moniter = len;
    TICKET_NUM = 3000;
    while( true ) {
        let id = parseInt( Math.random() * len );
        let status = pool[id].next().done;
        
        if ( status ) moniter--;
        
        if ( moniter == 0 ) {
            console.log("All ticket saled done...");
            break;
        }
    }
}

thread();

你可能感兴趣的:(前端)