Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - How to check if a function is running in worker thread in node?

I am trying to use worker_threads in node to run some expensive calculation without blocking the main thread.

Is it possible to check if the function is actually running in worker thread, just like using the performance tab in browser devtool?

question from:https://stackoverflow.com/questions/65878073/how-to-check-if-a-function-is-running-in-worker-thread-in-node

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the worker thread is running blocking code which is presumably why you pushed it to a worker thread in the first place, then it is blocked and it cannot communicate with you directly since it would have to receive a message from you and send a response for you to communicate with it, but if it's blocked doing something else, then it isn't processing messages so you can't talk to it until it's done.

Things you could do:

Have worker thread tell you when it started and when its done

When the function starts running, it sends a message to the main thread. The main thread gets that message and stores that state. When the function completes, it sends a message to the main thread that is has completed. The main thread will receive that and can update the state.

So, as long as the worker thread follows that logic reliably, then at any time, the main thread can just consult the state it has to know whether the worker thread last told it was running or done.

Test message processing responsiveness of the worker thread

Another option would be to send a message to the worker thread with some sort of uniqueID in it and note the time you sent the message. Then, the worker thread (when it is free to process that message) will respond to it and return back the same uniqueID. From the main thread, you can assume that if you don't get a quick response from the message you sent to the worker, then it must have been busy. You have to use the uniqueID because the response will come back sometime in the future and you have to know which responses to pay attention to and which might be old. This is basically just a test to see whether the worker thread is responding to messages quickly - thus indicating that it's not being blocked by some blocking operation that is currently running.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...