简体   繁体   English

有没有办法暂停和重启网络工作者?

[英]Is there a way to pause and restart the webworker?

I have a problem with my webworker and hope that somebody can help me.. I have a browser side with two buttons - one starts my worker (numbers are getting incremented), the other one pauses the worker.我的 webworker 有问题,希望有人能帮助我。我有一个带有两个按钮的浏览器端 - 一个启动我的工作人员(数字正在增加),另一个暂停工作人员。 If I click on the start button again, it should continue where it was interruptet.如果我再次单击开始按钮,它应该会在中断处继续。 In my javascript file I call the webworker based on the button click:在我的 javascript 文件中,我根据按钮点击调用网络工作者:

buttonClick: function () {
        if (typeof (this.w) == "undefined") {
            this.w = new Worker("theWorker.js");
            this.w.onmessage = this.workerResponse;
            this.w.postMessage("start");
        }
    }

My worker:我的工人:

onmessage = function(e) {
    if(e.data=="start"){
    run();
  }
}

function run(){
while(true){
    // numbers are getting incremented
}

My question is - how can I pause the worker?我的问题是 - 我怎样才能暂停工作人员? I don't want to terminate it, because then everything gets reseted, but I want to start again with the current number.我不想终止它,因为那样一切都会被重置,但我想用当前的数字重新开始。 I hope, anybody can help, If there is too less information.我希望,任何人都可以提供帮助,如果信息太少。 I can edit my post.我可以编辑我的帖子。 Thanks!谢谢!

Considering you are targeting latest browser, with access to SharedArrayBuffer and Atomics .考虑到您的目标是最新的浏览器,可以访问SharedArrayBufferAtomics Simplest solution is to pass SAB reference to the worker:最简单的解决方案是将 SAB 引用传递给工作人员:

main.js主程序

const sab = new SharedArrayBuffer(4);
const int32 = new Int32Array(sab);

buttonClick: function () {
        if (typeof (this.w) == "undefined") {
            this.w = new Worker("theWorker.js");
            this.w.onmessage = this.workerResponse;
            this.w.postMessage({kind:"start", sab});
        }
    }

pause: function() {
    Atomics.store(int32, 0, 1);
    Atomics.notify(int32, 0);
}

resume: function() {
    Atomics.store(int32, 0, 0);
    Atomics.notify(int32, 0);
}

...worker loop will wait for the byte to have particular value 1/0. ...工作循环将等待字节具有特定值 1/0。

worker.js工人.js

let int32;
onmessage = function(e) {
    if(e.data.kind=="start"){
        int32 = new Int32Array(e.data.sab);
        run();
    }
}

function run(){
    while(true){
        Atomics.wait(int32, 0, 1);
        // numbers are getting incremented
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM