javascript/python 協(xié)程實(shí)現(xiàn)并發(fā)調(diào)度的示例

協(xié)程,也被稱為“用戶態(tài)線程”抖剿,是可以由用戶去實(shí)現(xiàn)并發(fā)調(diào)度的一種語(yǔ)言設(shè)施醇滥。

設(shè)想,用戶并不知道協(xié)程礼预,只提供一般的阻塞api眠砾,用戶如下使用:

import time


time.sleep(1.0)
print('after 1s')

可以翻譯成協(xié)程實(shí)現(xiàn):

import time

def __thread():
 (yield time.sleep(1.0))
 print('after 1s')
 
scheduler.spawn(__thread() )

本方案示例了javascript里協(xié)程調(diào)度器,鑒于python generator和javascript generator模型的一致性托酸,應(yīng)很容易實(shí)現(xiàn)對(duì)應(yīng)python版本褒颈。

1.耗時(shí)操作提供異步版本API,如 settimeout 和 node.js API設(shè)計(jì)

//異步等待
settimeout(callback, ms)
 
//異步讀文件
var fs = require('fs');
fs.readFile(this.path, function(err, data) {
//...
});

2.包裝成 異步標(biāo)記對(duì)象

class coTime extends iYield {
    constructor(time) {
        super();
        this.time = time;
    }

    start(task) {
        task.yield.done = 'waiting';
        setTimeout(() => {
            task.yield = task.cofunc.next(this.time);
        }, this.time);
    }
}

//最終提供的API
function wait(ms) {
    return new coTime(ms);
}

3.如多線程一樣使用

// 創(chuàng)建10個(gè)(用戶)線程
for (let i = 0; i < 10; ++i) {
    coManager.thread(
        (function*() {
            while (true) {
                let time = yield wait(Math.random() * 2000);
                console.log(`thread ${i} wait:` + time);
            }
        })()
    );
}

這里 coManager是協(xié)程調(diào)度器获高,原理是,實(shí)現(xiàn)一個(gè)異步任務(wù)隊(duì)列吻育,每次異步等待時(shí)念秧,將協(xié)程中斷(suspend),每異步返回時(shí)布疼,將中斷的協(xié)程繼續(xù)摊趾,完整可執(zhí)行的代碼如下

// 并發(fā)任務(wù)對(duì)象
class coTask {
    constructor(cofunc) {
        this.cofunc = cofunc;
        this.yield = cofunc.next();
    }
}

class iYield {
    // 開始異步
    start(task) {}
}

// 讀文件異步調(diào)用
class coReadFile extends iYield {
    constructor(path) {
        super();
        this.path = path;
    }

    start(task) {
        item.yield.done = 'waiting';
        var fs = require('fs');
        fs.readFile(this.path, function(err, data) {
            if (err) {
                task.yield = task.cofunc.throw(err);
            } else {
                task.yield = task.cofunc.next(data); //done and next
            }
        });
    }
}

// helper
function readFile(path) {
    return new coReadFile(path);
}


// 定時(shí)器異步對(duì)象
class coTime extends iYield {
    constructor(time) {
        super();
        this.time = time;
    }

    start(task) {
        task.yield.done = 'waiting';
        setTimeout(() => {
            task.yield = task.cofunc.next(this.time);
        }, this.time);
    }
}

function wait(ms) {
    return new coTime(ms);
}

// 協(xié)程管理器,負(fù)責(zé)調(diào)度
class CoroutineManager {
    constructor() {
        this.taskLs = [];
        this.update.bind(this);
        setInterval(() => {
            let taskLs = this.taskLs;
            this.taskLs = [];
            // 任務(wù)隊(duì)列輪循
            for (let item of taskLs) {
                if (item.yield.done != true) {
                    this.taskLs.push(item);
                }
            }
            for (let item of taskLs) {
                if (item.yield.done === 'waiting') {
                    continue;
                } else if (item.yield.value instanceof iYield) {
                    item.yield.value.start(item);
                } else {
                    item.yield = item.cofunc.next();
                }
            }
        }, 1);
    }

    // 開(用戶)線程
    thread(cofunc) {
        let yValue = cofunc.next();
        if (yValue.done) {
            return;
        }
        this.taskLs.push({ yield: yValue, cofunc });
    }
}

let coManager = new CoroutineManager();

// 創(chuàng)建10個(gè)(用戶)線程
for (let i = 0; i < 10; ++i) {
    coManager.thread(
        (function*() {
            while (true) {
                let time = yield wait(Math.random() * 2000);
                console.log(`thread ${i} wait:` + time);
            }
        })()
    );
}

python協(xié)程:

from browser import timer as systimer;
import random
import time

class Co:
    def __init__(self):
        pass
    
    def getVal(self):
        return None
        
class timer(Co):
    def __init__(self, last):
        self.last = last
        self.start = time.clock()
    
    def isDone(self):
        last = time.clock()-self.start
        if last>=self.last:
            return True
        else:
            return False
    
    def getVal(self):
        return int(random.random()*self.last)
    

class Scheduler:
    def __init__(self):
        self.working = []
        self.starting = []
        self.timer = None
        
    def run(self):
        self.timer = systimer.set_interval(lambda: self.update(), 20);
        
    def update(self):
        starting = self.starting;
        self.starting = []
        for fun in starting:
            try:
                print(1)
                r = next(fun)
                print(2)
                while not isinstance(r, Co):
                    r = next(fun)
                self.working.append((fun, r))
            except StopIteration:
                pass
            except Exception as ex:
                print(ex)
                
        working = self.working;
        self.working = []
        for (fun, r) in working:
            try:
                if r.isDone():
                    val = r.getVal()
                    r = fun.send(val)
                    while not isinstance(r, Co):
                        r = next(fun)
                    self.working.append((fun, r))
                else:
                    self.working.append((fun, r))
            except StopIteration:
                pass
            except Exception as ex:
                print(ex)
                        
    def startCorotine(self, fun):
        self.starting.append(fun)


scheduler = Scheduler()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末游两,一起剝皮案震驚了整個(gè)濱河市砾层,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌贱案,老刑警劉巖肛炮,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異宝踪,居然都是意外死亡侨糟,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門瘩燥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秕重,“玉大人,你說我怎么就攤上這事厉膀∪茉牛” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵服鹅,是天一觀的道長(zhǎng)凳兵。 經(jīng)常有香客問我,道長(zhǎng)企软,這世上最難降的妖魔是什么留荔? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上聚蝶,老公的妹妹穿的比我還像新娘杰妓。我一直安慰自己,他們只是感情好碘勉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布巷挥。 她就那樣靜靜地躺著,像睡著了一般验靡。 火紅的嫁衣襯著肌膚如雪倍宾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天胜嗓,我揣著相機(jī)與錄音高职,去河邊找鬼。 笑死辞州,一個(gè)胖子當(dāng)著我的面吹牛怔锌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播变过,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼埃元,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了媚狰?” 一聲冷哼從身側(cè)響起岛杀,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎崭孤,沒想到半個(gè)月后类嗤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辨宠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年土浸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片彭羹。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡黄伊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出派殷,到底是詐尸還是另有隱情还最,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布毡惜,位于F島的核電站拓轻,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏经伙。R本人自食惡果不足惜扶叉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一勿锅、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧枣氧,春花似錦溢十、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至酪劫,卻和暖如春吞鸭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背覆糟。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工刻剥, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人滩字。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓造虏,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親踢械。 傳聞我的和親對(duì)象是個(gè)殘疾皇子酗电,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容