1

I have a main thread, which contains a handleSubmit:

 function handleSubmit({ ref }) { // ref is a react useRef
        const worker = new Worker('Workers/SolveWorker.js');
        worker.postMessage(ref);

I also have a handleCancel, which mutates my useRef:

function handleCancel() {
        allowedToRunRef.current = false;
    }

Inside my worker:

onmessage = function (e) {
  const startTime = Date.now();
  while (Date.now() < startTime + 5000 && e.data.allowedToRunRef.current) {
    // do nothing
  }
  postMessage(finalSolutions);
};

My idea is that when I submit my query, it starts a computation inside a webworker thread. If a user wants to cancel the computation, they can do so, mutating the flag, which kills the while loop inside the worker.

However, this does not work, as you cannot pass things by reference to web workers, it seems.

How can I fix the problem of allowing for a shared flag, to allow for premature cancellation?

713sean
  • 313
  • 11
  • If you want to create a cancellable API, you'll need to accept more than one type of message in the worker (one being a cancellation message). Another method is to simply [terminate](https://developer.mozilla.org/en-US/docs/Web/API/Worker/terminate) the worker from the host if that's the desired behavior. The question does not currently clearly describe the intention. Can you update it to clarify? – jsejcksn Jan 17 '23 at 22:53
  • You can await every nth iteration for a new task, this way your worker will be able to handle new messages. Alternatively, in supporting envs, you can (ab)use Atomics to create a sync messaging system between both ends. See this related Q/A: https://stackoverflow.com/questions/54478195/how-to-allow-web-workers-to-receive-new-data-while-it-still-performing-computati/54481612#54481612 – Kaiido Jan 18 '23 at 00:21
  • Kaiido- thank you for your response. I am not able to await nth iterations most likely, as it creates too much speed overhead. jsejcksn, let me think and then edit, thanks. – 713sean Jan 18 '23 at 00:35

0 Answers0