How to prevent HTML5 Web Workers from locking up thus correctly responding to messages from parent

后端 未结 3 1129
梦谈多话
梦谈多话 2021-02-06 02:45

I\'m using web workers to do some CPU intensive work but have the requirement that the worker will respond to messages from the parent script while the worker is still processin

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 03:15

    I ran into this issue myself when playing with workers for the first time. I also debated using setInterval, but I felt that this would be a rather hacky approach to the problem (and I had already went this way for my emulated multithreading). Instead, I settled on terminating the workers from the main thread (worker.terminate()) and recreating them if the task that they are involved in needs to be interrupted. Garbage collection etc seemed to be handled in my testing.

    If there is data from these tasks that you want to save, you can always post it back to the main thread for storage at regular intervals, and if there is some logic you wish to implement regarding whether they are terminated or not, you can post the relevant data back at regular enough intervals to allow it.

    Spawning subworkers would lead to the same set of issues anyway; you'd still have to terminate the subworkers (or create new ones) according to some logic, and I'm not sure it's as well supported (on chrome for example).

    James

提交回复
热议问题