Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using onMessage and postMessage in a worker and main thread #322

Open
ari62 opened this issue Nov 29, 2020 · 3 comments
Open

Using onMessage and postMessage in a worker and main thread #322

ari62 opened this issue Nov 29, 2020 · 3 comments
Labels

Comments

@ari62
Copy link

ari62 commented Nov 29, 2020

Hello, please provide an example of using onMessage and postMessage from both the worker side and the main thread side using Typescript. The object returned from spawn doesn't seem to include those methods and I dont see how to call them from within expose as well.

Thank you

@andywer
Copy link
Owner

andywer commented Nov 30, 2020

Hey @ari62. You are not supposed to use the worker directly when using threads.js.

What's your use case that you want to go low-level?

@ari62
Copy link
Author

ari62 commented Dec 13, 2020

Hi Andy, I think what i was trying to do is use setInterval to do a repeated task in a thread and then send a message to the thread to stop the setInterval. I think if I just stop the thread (using Thread.terminate) and don't call clearInterval, I risk memory leaks. I also needed to send data from the thread to the originating code. I guess any use case where you need to send a message to a thread or from a thread to the originating code would be the general use case for posting message both to and from threads.

@andywer
Copy link
Owner

andywer commented Dec 13, 2020

Ahhh, in this case what you want is #273 😉

Because using the low-level postMessage seems like a rather bad idea. For your use case, however, I don't see a need for any of that. Why not just do something like this?

// worker code
import { expose } from "threads/worker"

const interval = setInterval(doStuff, 1234)

expose({
  // …
  stop() {
    clearInterval(interval)
  }
})

Btw, I don't think you're at risk of memory leaks if you call Thread.terminate() as you terminate the whole thread anyway. That should free up all resources used by the thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants