My question, though, was intended to ask whether this simultaneous invocation
of the load image callback for the same process was something that is supposed
to be possible based on how the kernel is supposed to be invoking the
callback. Somehow, that process is attempting to load 2 different DLLs at the
same time and the notifications of those events are being delivered. Given
that there is supposed to be other locking going on in the process itself
while DLLs are being loaded and mapped into memory I’m at a loss to explain
the why/how. All I can do is respond to what is actually happening and deal
with it.


    let flag = false
    function doSomething() {
      flag = true
      // More code (that doesn't change `flag`)...

      // We can be sure that `flag` here is true.
      // There's no way another code block could have changed
      // `flag` since this block is synchronous.
    }


[ updated ** 2019-03-30 05:44:34 -0600  ** ](/answers/210948/revisions/)


I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu) for 386(486) AT clones. ... and it probably never will support anything other than AT-harddisks, as that's all I have :-(.
-Linus


[ August 19, 2020 at 9:18 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-3454)


And, one more query: Is using waitkey(1), optimal for real-time application?


Seen: **2,461 times**


Since we are forking processes, we want to take advantage of our OS’s
scheduling and all the cores of our machine. Just as you can listen to music
and browse the internet at the same time, you can fork two processes and
execute all the tasks in parallel.


[ With Android, how do I pass control back to the main thread? [closed]
](/question/10401/with-android-how-do-i-pass-control-back-to-the-main-thread/)


Reply


[ openmp and thread with opencv ](/question/14240/openmp-and-thread-with-
opencv/)


The NTDDK documentation for PLOAD_IMAGE_NOTIFY_ROUTINE states “The operating
system calls the driver’s load-image notify routine at PASSIVE_LEVEL inside a
critical region with normal kernel APCs always disabled and sometimes with
both kernel and special APCs disabled.”.


So, is the problem solved? Well, technically yes — but while we have solved
the problem, we’re still using a lot more memory than a multithreaded
solution.


Jest is feature-rich testing framework that comes with several in-built
features that make it powerful and easy to use.


Copyright [ OpenCV foundation ](http://www.opencv.org) , 2012-2018. Content on
this site is licensed under a [ Creative Commons Attribution Share Alike 3.0
](http://creativecommons.org/licenses/by-sa/3.0/legalcode) license.


For additional information, check out [ the ` worker_threads ` documentation
](https://nodejs.org/docs/latest-v10.x/api/worker_threads.html) .


you should **never** try to do that !


[ Hi there! Please sign in ](/account/signin/?next=/question/210946/how-to-
update-cvnamedwindow-in-multi-threading-environment/) [ help ](/help/ "help")


Like with database connections, we need a pool of processes that are ready to
be used, run a task at a time in each one, and reuse the process once the task
has finished. This looks complex to implement, and it would be if we were
building it from scratch!


We’ll get the results in the callback once they are available. Then, no other
JavaScript code is executed until our callback finishes its execution.


[ July 8, 2022 at 4:25 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-28276)


Any have an idea about the execution of the worker thread. Does this worker
thread utilize all System Core or run on single thread?


  * [ Home ](/)
  * [ Categories ](/categories)
  * [ FAQ/Guidelines ](/guidelines)
  * [ Terms of Service ](https://www.osr.com/osr-community-terms-service/)
  * [ Privacy Policy ](https://www.osr.com/osr-community-privacy-policy/)


    // Runs `script.js` in a new environment without sharing memory.
    const service = createService('script.js')
    // We send an input and receive an output
    service.compute(data, function(err, result) {
      // result available here
    })


At first I thought you had two callbacks for the same DLL, which I don’t
think is possible at the same time.
But for two DLLs - yeah, it’s possible and how you never saw it is beyond
me ![:slight_smile:](/images/emoji/twitter/slight_smile.png?v=12) It is so
common.


When we’re finished, we wait for the worker thread to send us a message by
listening to the ` message ` event. Implement the service:


aewarnick's AvatarJoin Date
Dec 2002
Posts
1,037
Re: Multithreading, Callbacks and Synchronization
Enough MS Windows bashing....
I appreciate your maxim: "Users of MS Windows should not be programmers", but maybe you can help anyway.
You did misunderstand CornedBee.


##  Stats


Think of any CPU-intensive task, like video compression, complex calculations,
encryption and decryption, etc. You can perform all of these on the worker
thread while simultaneously running your main app on the main thread.


[ January 3, 2021 at 11:49 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-4801)


##  The history of single-threaded JavaScript


No thanks


Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Reply With QuoteReply With Quote  Feb 28th, 2005, 05:49 PM#3
Phenix Phenix is offline
Thread Starter
Addicted Member


Our Node.js applications are only sort of single-threaded, in reality. We can
run things in parallel, but we don’t create threads or sync them.


I guess I'll have to explain my app a little more. All I really want to do is get the text from an external app whenever that text is updated so that I can log it. The external app is using a MSHFlexGrid, so it is not as simple as calling GetWindowText. If there is a way I could call TextMatrix on the external app's MSHFlexGrid, I would not use an image processing approach.


Buy and read the book I mentioned. Then we can discuss the trickier parts of how Windows works.
All the buzzt
CornedBee


That’s it! This is the simplest example, but we can yet build more complex
things. For example, we could send multiple messages from the worker thread
indicating the execution status if we need to provide feedback.


Reply


So, yes, adding appropriate synchronization will resolve the problem. What I’m
trying to figure out is how/why this started happening to begin with. I agree
that the code in the callback function is not behaving correctly and should
fail exactly as it is failing in this scenario. Not knowing what caused the
change in behavior on the part of the kernel is what I’m trying to determine.
If I can get a proper understanding of the rules that the kernel follows as
“contractual behavior” regarding serialized vs. simultaneous invocation of
these event notification types of callback functions then I can ensure that
the various callback methods implemented in this driver are using appropriate
synchronization mechanisms.


Hello,


[ berak ](/users/2130/berak/)
32993  ●  7  ●  81  ●  312


17. ![](https://secure.gravatar.com/avatar/3a1615b744ecc9f649ea997c392e8eec?s=36&d=mm&r=g) **ravirajkakade** says:


How do Worker_Threads differ from Clusters, which also has workers? [
https://nodejs.org/docs/latest-v14.x/api/cluster.html
](https://nodejs.org/docs/latest-v14.x/api/cluster.html) . ?


####  Using AWS Lambda and CloudFront to optimize image handling


###  Share this:


##  Conclusion


To avoid these side effects, let’s discuss some of the best practices
regarding how to manage using workers in your app:


  Overview  ï

Execution management in ROS 2 is explicated by the concept of Executors. An
Executor uses one or more threads of the underlying operating system to invoke
the callbacks of subscriptions, timers, service servers, action servers, etc.
on incoming messages and events. The explicit Executor class (in [
executor.hpp
](https://github.com/ros2/rclcpp/blob/foxy/rclcpp/include/rclcpp/executor.hpp)
in rclcpp, in [ executors.py
](https://github.com/ros2/rclpy/blob/foxy/rclpy/rclpy/executors.py) in rclpy,
or in [ executor.h
](https://github.com/ros2/rclc/blob/master/rclc/include/rclc/executor.h) in
rclc) provides more control over execution management than the spin mechanism
in ROS 1, although the basic API is very similar.

In the following, we focus on the C++ Client Library _rclcpp_ .


####  How to build a custom GPT: Step-by-step tutorial


I am sorry, but the Oracle was mistaken. You cannot help us.
-Matrix video game


As we said before, if we do this, it will take too much time to process the
whole array and the rest of the JavaScript execution will be blocked. Let’s
split this into smaller chunks and use ` setImmediate(callback) ` :


You have to have synchronization, as find is not atomic itself, and find +
remove surely isn’t.


We can’t just add threads as a new set of classes or functions available —
we’d probably need to change the language to support multithreading. Languages
that currently support it have keywords such as ` synchronized ` to make
threads cooperate.


##  Comments


Besides, the code now is asynchronous, and if we depend on third-party
libraries, we might not be able to split the execution into smaller chunks.


##  Multithreading alternatives to worker threads


Are you threatening me, Master Jedi?
-Chancellor Palpatine
Reply With QuoteReply With Quote
Quick Navigation C and C++ Top
« Previous Thread | Next Thread »
HomeVBForumsOther LanguagesC and C++Multithreading, Callbacks and Synchronization [RESOLVED]
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
[VIDEO] code is On
HTML code is Off
Forum Rules


[ ![JeyP4 gravatar image](/upfiles/avatars/JeyP4/resized/32/Untitled.png)
](/users/408655/jeyp4/)


Reply


const worker = new Worker(‘./service.js’, { workerData });


##  Running parallel processes in the background, without threads


The NTDDK documentation for PCREATE_PROCESS_NOTIFY_ROUTINE states “The
operating system calls the driver’s process-notify routine at PASSIVE_LEVEL
inside a critical region with normal kernel APCs disabled.”.


the article at [ https://medium.com/swlh/understanding-nodejs-worker-
thread-6212b95a0928 ](https://medium.com/swlh/understanding-nodejs-worker-
thread-6212b95a0928) blatantly plagiarizes you word for word for most of it
and the rest of it are very lazily edited with slightly different wording.


1 follower


I read the OSR article “Understanding Critical Regions” and am very clear in
my understanding that a critical region is not a critical section. There is
explicit mention that acquiring any Spinlocks, Kernel Mutexes, Fast Mutexes or
Guarded Mutexes will implicitly result in entering a critical region, while
other locking/synchronization constructs do not implicitly enter a critical
region.


Regards, Dejan.


JavaScript and Node.js were not meant to be used for CPU-bound tasks. Since
JavaScript is single-threaded, this will freeze the UI in the browser and
queue any I/O events in Node.js.


Learn a lot from this article


Question. Do you know that the character "?" means I'm asking a question? Question. Do you know that spoken inflection also provides the same cue? So please don't say, "Question" before you ask your question. Believe me I'll know.


](https://blog.logrocket.com/using-aws-lambda-cloudfront-optimize-image-
handling/)


[ ![](https://blog.logrocket.com/wp-
content/uploads/2019/04/albertogimeno.jpeg?w=150&h=150&crop=1)
](https://blog.logrocket.com/author/albertogimeno/)


12. ![](https://secure.gravatar.com/avatar/92d034a2195d9910ba29dc66db775e26?s=36&d=mm&r=g) **MARCUS AURELIUS MINERVINO JUNIOR** says:


In the past year my development responsibilities expanded to include the
maintenance & troubleshooting of a software driver written in C++ using the
DriverWorks framework. Much of the code shows a revision history with very few
changes made over the 15+ year span of time since it was originally written.
Recently, a bugcheck started occurring and I was able to track down the root-
cause, which is a double-remove operation being performed on an item in a
doubly linked list. While analyzing the source code and a crash dump I noticed
that the callback function registered via PsSetLoadImageNotifyRoutine()
appears to be getting called simultaneously by two different threads reporting
image load events for the same process, yet is coded with an implicit
assumption that image load notifications for a given process will occur
sequentially, not concurrently. Obviously, that assumption is incorrect based
on the content of the crash dump and the double-remove operation that caused
the bugcheck.


18. ![](https://secure.gravatar.com/avatar/3c10844941f5b7f8b3facb69d65fc122?s=36&d=mm&r=g) **anon** says:


[ Powered by Askbot version 0.10.2 ](http://askbot.com)


Usually, as we said before, the code is minimal and fast enough. However, in
this case, we have many results and we need to perform heavy computations on
them.


There is still a question, are JavaScript and NodeJS single-threaded or multi-
threaded?


I am sorry, but the Oracle was mistaken. You cannot help us.
-Matrix video game


This made things easier for developers because JavaScript was initially a
language that was only useful for adding interaction to webpages, form
validations, and so on. None of this required the complexity of
multithreading.


Yeah


##  Stop guessing about your digital experience with LogRocket


[ Finding features in several threads ](/question/3653/finding-features-in-
several-threads/)


If you plan to use worker threads in your Node project, you should keep in
mind all the other best practices we mentioned above to get the best out of
performing CPU-intensive tasks in your app. In the case of I/O-bound tasks,
you should consider making use of Node.js built-in asynchronous I/O
operations.


The result would be that, after both threads have accessed the variable, it
has a few bytes changed by one thread and a few bytes changed by the other
thread. Thus, it will not result in any valid value.


Very informative and well written. Thanks


Great article, clear all doubts related to complex topic (worker thread)


[ August 18, 2019 at 10:09 pm  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-367)


Reply


###  More great articles from LogRocket:


However, concurrency can be a very hard problem to solve. Having many threads
accessing the same memory can produce race conditions that are very hard to
reproduce and fix.


If 1 callback receives an image and performs some image-processing. How can
the output image be shown in multi-threading environment? By multi-threading I
mean, if that particular callback( _depthCallback_ ) can be invoked by more
than one thread.


Node.js v10.5.0 [ introduced the ` worker_threads ` module
](https://nodejs.org/en/blog/release/v10.5.0/) , which has been stable since
Node.js v12 LTS. In this post, we will discuss what this worker thread module
is and why we need it, touching on concepts like the historical reasons for
concurrency in JavaScript, common problems and their solutions, and more.


Our Node.js application just invokes the function and doesn’t block the
execution of other pieces of code. It will get notified through the callback
when the query is done, and we will receive the result.


###  Using worker threads for multiple tasks


5. ![](https://secure.gravatar.com/avatar/e589385454bd1093fadcb4708e2b150c?s=36&d=mm&r=g) **Nifemi** says:


The Web Workers API is more mature and is [ well-supported by modern browsers
](https://caniuse.com/#search=web%20workers) . It can be useful if you are
doing crypto mining, compressing/decompressing, image manipulation, computer
vision tasks such as face recognition, and other such processes in your web
application.


Whatever. Messages retain the time they were queued, but WM_PAINT might just be a special case, because it is never queued like the other messages. Instead, a flag is set. A pecularity of WM_PAINT is that it's always the last message to be retrieved.
All the buzzt
CornedBee


In summary, worker threads are well-suited for parallelizing CPU-bound tasks,
data processing, and other computationally intensive operations on the server
side. Meanwhile, web workers are commonly used in web applications to offload
intensive computations from the main thread, keeping the user interface
responsive.


* [ #node ](https://blog.logrocket.com/tag/node/)


As such, there is no original send time of WM_PAINT. Neither is a WM_PAINT ever "retrieved from the queue", as such. Instead, the QS_PAINT flag stays set until a call to ValidateRect, ValidateRgn or EndPaint validates all invalidated areas.
As such, it is not possible for WM_PAINT messages to stack up.


[ January 11, 2022 at 6:15 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-9774)


LogRocket’s Galileo AI watches every session, surfacing impactful user
struggle and key behavior patterns.


Also of note, thread create/delete notifications don’t even happen within a
critical region, and the driver code I’m working has a function for that
callback that makes other calls that ultimately lead to obtaining & releasing
a lock while manipulating a linked list. I need to determine if the lock
mechanism being used falls under the category of locks that implicitly enter a
critical region or of its using one of the other types that do not have that
behavior. If it is using the latter type, then that represents another place
where a fault could occur in the driver code leading to a deadlock or some
other eventually fatal problem if the thread were to be interrupted while it
held the lock.


1. ![](https://secure.gravatar.com/avatar/0ca64b67aec04f665f1f88341baaef20?s=36&d=mm&r=g) **Niels Andersen** says:


Hi all,


CornedBee
Buy and read ... Jeffrey Richter ... "Application Programming with Microsoft Windows"
I usually prefer an ISBN, but it came up on google as the first hit.


Great article………. Kudos!!!


Yes, there is synchronization involved with access to the list as it’s a class
derived from KInterlockedList<> [part of the DriverWorks framework] in terms
of “add”, “find” and “remove” operations. However, the code in the callback,
as originally written, performs a “find” followed by a “remove” and there is
no overarching lock being held as the find is performed and then a subsequent
remove being performed if the find was successful. That’s where things are
blowing up as there are 2 threads entering the callback at the same time for
the same process, and so they momentarily synchronize on the “find” but then
things become non-deterministic as they execute a few more instructions before
attempting to perform the “remove” operation. This results in one of the first
“remove” operation to be complete being successful followed by the
second/redundant attempt to remove the item from the list causing a bugcheck.


Reply


[ READ THE
BLOG POST ](https://blog.logrocket.com/galileo-ai)


1. ![](https://secure.gravatar.com/avatar/95da8531267310d384681c953762007b?s=36&d=mm&r=g) **arunsharma333** says:


Apr 10, 2024 ⋅ 7 min read


[ none ](/questions/scope:all/sort:activity-desc/tags:none/page:1/) ×


Can we reuse the same forked process? Sure, but sending different heavy,
synchronously-executed workloads inside the forked process creates two
problems:


You can probably look for a https://itnext.io/a-workerpool-from-scratch-in-
typescript-and-node-c4352106ffdegeneric pool implementation or a [ specific
one such as ` workerpool ` in npm ](https://www.npmjs.com/package/workerpool)
instead of creating your own pool implementation. Node.js provides [ the `
AsyncResource ` class ](https://nodejs.org/api/async_context.html#using-
asyncresource-for-a-worker-thread-pool) to provide proper async tracking of a
worker pool.


Table of contents  __ __


[ ![OpenCV answers logo](/upfiles/logo_2.png) ](/questions/)


This is great if all we do is asynchronous I/O. Our code consists of small
portions of synchronous blocks that run fast and pass data to files and
streams. As a result, our JavaScript code is so fast that it doesn’t block the
execution of other pieces of JavaScript.


###  Best practices while using worker threads for CPU-intensive tasks


Alberto Gimeno


Let’s put together some of the examples we’ve seen so far to perform a CPU-
intensive task and see how the worker thread would not block the event loop:


[ How to speed up this code implemented OpenCV ](/question/7166/how-to-speed-
up-this-code-implemented-opencv/)


13. ![](https://secure.gravatar.com/avatar/a9cf3fd36090ee6046a7724f4a11efde?s=36&d=mm&r=g) **olumide onafowope** says:


[ FLANN algorithm cannot find any descriptor ](/question/11449/flann-
algorithm-cannot-find-any-descriptor/)


Are you threatening me, Master Jedi?
-Chancellor Palpatine
Reply With QuoteReply With Quote  Feb 28th, 2005, 02:55 PM#2
CornedBee CornedBee is offline
Kitten

CornedBee's AvatarJoin Date
Aug 2001
Location
In a microchip!
Posts
11,594
Re: Multithreading, Callbacks and Synchronization
Actually, the Windows message model should made it impossible for a WM_PAINT to be queue while another one is not yet processed.


For example, when the driver goes active, it does the following:


The reality is that we can already do background processing in Node.js. We can
[ fork the process
](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)
and do exactly that using message passing, which you can imagine as simply as
passing a message from one process to another. This achieves the following
goals:


If your heavy processing is done in a loop, there is a simple way to yield the
main thread that does not require refactoring your code. Simply do “await new
Promise(r => setTimeout(r, 10));” every X iteration of the loop.


[ July 18, 2019 at 10:59 pm  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-193)


JavaScript was conceived as a single-threaded programming language that ran in
a browser. Being single-threaded means that only one set of instructions is
executed at any time in the same process — in this case, the browser, or just
the current tab in modern browsers.


A lot more time is spent waiting for I/O events to happen than JavaScript code
being executed. Let’s see this with a quick example:


Threads are still very lightweight in terms of resources compared to forked
processes. This is why worker threads were born.


What you can do is:
...
Yeah, my first thought was to go with threads, but then I also thought I may already have "built-in" threading. Thanks.


Please note: OpenCV answers requires javascript to work properly, please
enable javascript in your browser, [ here is how
](https://www.google.com/support/bin/answer.py?answer=23852)


##  Why we will never have multithreading in JavaScript


[ NTDEV  ](/c/ntdev/7)


RegisterHelp
User Name

Password

 Remember Me?


[ asked ** 2019-03-30 04:49:03 -0600  ** ](/questions/210946/revisions/)


In other words, everything runs in parallel except for our JavaScript code.
Synchronous blocks of JavaScript code are always run one at a time:


  * Debugging and profiling can be more complex compared to a single-threaded application due to the involvement of multiple processes
  * Primarily suitable for CPU-intensive tasks; less effective for I/O-bound tasks


    db.findOne('SELECT ... LIMIT 1', function(err, result) {
      if (err) return console.error(err)
      console.log(result)
    })
    console.log('Running query')
    setTimeout(function() {
      console.log('Hey there')
    }, 1000)


##  Is Node.js single-threaded or multithreaded?


##  The need for threads to perform CPU-intensive tasks


PsSetCreateProcessNotifyRoutine(), PsSetCreateThreadNotifyRoutine() and
PsSetLoadImageNotifyRoutine() are used by this driver.


Reply


1. ![](https://secure.gravatar.com/avatar/cf5ffb86e59829914a08a30b954875b6?s=36&d=mm&r=g) **Matt Angelosanto** says:


[ __ GitHub ](https://github.com/opencv)


[ March 25, 2023 at 7:02 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-34616)


[ ![Jest Adoption Guide: Overview, Examples, And
Alternatives](https://blog.logrocket.com/wp-content/uploads/2024/04/Jest-
adoption-guide-Overview-examples-alternatives.png?w=420)
](https://blog.logrocket.com/jest-adoption-guide/) [


##  Using ` worker-farm ` to pool threads


  * Worker threads in Node.js are part of the Node.js runtime and are specifically designed for server-side JavaScript
  * Web workers are a feature of web browsers and are designed for client-side JavaScript running in the browser


You can share memory with worker threads by passing ` ArrayBuffer ` or `
SharedArrayBuffer ` objects, which are specifically meant for this process.
These objects allow you to avoid the need for data serialization, but you
should only use them if you need to do [ CPU-intensive tasks with large
amounts of data ](https://blog.logrocket.com/use-cases-for-node-workers/) .


_**Editor’s note** : This post was last updated by [ Elijah Agbonze
](https://blog.logrocket.com/author/elijahtrillionz/) on 8 January 2024 to
reflect any updates and changes in the most recent Node.js version, add more
detail about worker threads, and compare other multithreading methods. It was
previously updated on 18 January 2022 to include some new information about
the Web Workers API and web workers in general, improve and add definitions of
key terms, and reflect stable support for the ` worker_threads ` module. _


16. ![](https://secure.gravatar.com/avatar/4a200c9c5de9d0df198210601ad659e7?s=36&d=mm&r=g) **SAli Mousavi** says:


But if the callback queues this up for me, I don't have to write a multithreaded image processing function nor concern myself with synchronization. Does the callback operate the way I have written in my first paragraph?
Last edited by Phenix; Mar 1st, 2005 at 10:31 AM. Reason: [RESOLVED]
Circa 1995
Engineer - I think we should put our website address on our paper catalogs.
Vice President - Don't get too excited about this internet thing.


9. ![](https://secure.gravatar.com/avatar/476fb22664aa5d7cd1977e65bb4bf794?s=36&d=mm&r=g) **fahad abid** says:


node --experimental-worker index.js


Well, hold on. This is a solution, but it’s not the ideal solution. Forking a
process is expensive and slow — it means running a new virtual machine from
scratch and using a lot of memory, since processes don’t share memory.


All times are GMT -5. The time now is 12:52 PM.


[ Clustering ](https://blog.logrocket.com/optimizing-node-js-app-performance-
clustering/) |  This module streamlines the generation of child processes,
each operating on a distinct core, and offers a shared server port to
facilitate load balancing. It enables us to create a cluster of processes,
optimizing the way we utilize multi-core systems.  |


    // main app
    const workerFarm = require('worker-farm')
    const service = workerFarm(require.resolve('./script'))

    service('hello', function (err, output) {
      console.log(output)
    })

    // script.js
    // This will run in forked processes
    module.exports = (input, callback) => {
      callback(null, input + ' ' + 'world')
    }


[ __ Official site ](https://opencv.org)


The NTDDK documentation for PCREATE_THREAD_NOTIFY_ROUTINE states “The driver’s
thread-notify routine runs at IRQL = PASSIVE_LEVEL or APC_LEVEL.”.


To run the example, remember to use the ` --experimental-worker ` flag if you
are using any version prior to Node.js 11.7:


11. ![](https://secure.gravatar.com/avatar/67fb0ca2d36af847328005b2e88b15d2?s=36&d=mm&r=g) **neil** says:


with LoadImageNotify(…) declared as:


[ multithreaded cascade classifire ](/question/4286/multithreaded-cascade-
classifire/)


14. ![](https://secure.gravatar.com/avatar/0f48f99a405123e48a4833a64e59bb3b?s=36&d=mm&r=g) **Oscar Martinez** says:


Apr 9, 2024 ⋅ 12 min read


Explore Termino.js, an open source library for integrating web-based terminals
into applications, in this introduction article.


Tracing messages show LoadImageNotify() being entered by thread A with
ProcessId == X, but before thread A returns from the function, thread B also
enters LoadImageNotify() with ProcessId == X, albeit for a different
FullImageName string value.


Powered by [ Discourse ](https://www.discourse.org) , best viewed with
JavaScript enabled


Apr 11, 2024 ⋅ 6 min read


![](https://blog.logrocket.com/wp-content/uploads/2022/08/rocket-button-
icon.png) Learn more →  ](https://lp.logrocket.com/blg/learn-more)


2. ![](https://secure.gravatar.com/avatar/f6ab4a707a73df1ab1aece5beea6feba?s=36&d=mm&r=g) **Moses Peter** says:


This forum is disabled, please visit [ https://forum.opencv.org
](https://forum.opencv.org)


    db.findAll('SELECT ...', function(err, results) {
      if (err) return console.error(err)

      // Heavy computation and many results
      for (const encrypted of results) {
        const plainText = decrypt(encrypted)
        console.log(plainText)
      }
    })


          .update(new Array(10000).fill(item).join("."))
          .digest("hex");
      }
      parentPort.postMessage(codes);
    }


######  Advisory boards aren’t only for executives.  Join the LogRocket
Content Advisory Board today  →


That's pretty straightforward and needs minimal synchronization.
an ending
Reply With QuoteReply With Quote  Feb 28th, 2005, 07:18 PM#5
aewarnick aewarnick is offline
Frenzied Member


Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Reply With QuoteReply With Quote  Mar 1st, 2005, 10:30 AM#7
Phenix Phenix is offline
Thread Starter
Addicted Member


###  Web workers vs. worker threads


##  Question Tools


Are you threatening me, Master Jedi?
-Chancellor Palpatine
Reply With QuoteReply With Quote  Feb 28th, 2005, 07:01 PM#4
azteched azteched is offline
Fanatic Member


[ OSR Developer Community ](/)


In single threading ` ros::spin() ` , above code runs well. And update image
normally. In multi-threading ` ros::AsyncSpinner spinner(2) ` , node gets
hang, and can't be stopped by Ctrl+C.


[ ![](https://blog.logrocket.com/wp-content/uploads/2023/07/Screen-
Shot-2023-07-06-at-7.43.53-AM.png)


status = PsSetLoadImageNotifyRoutine(&LoadImageNotify);


[ Ryan Dahl ](https://github.com/ry) saw this limitation as an opportunity
when he created Node.js. He wanted to implement a server-side platform based
on asynchronous I/O to avoid a need for threads and make things a lot easier.


Reply


add a comment


[ ![JeyP4 gravatar image](/upfiles/avatars/JeyP4/resized/16/Untitled.png)
](/users/408655/jeyp4/) [ JeyP4 ](/users/408655/jeyp4/) (  2019-03-30 04:51:46
-0600  )  edit


  Outlook  ï

While the three Executors of rclcpp work well for most applications, there are
some issues that make them not suitable for real-time applications, which
require well-defined execution times, determinism, and custom control over the
execution order. Here is a summary of some of these issues:

  1. Complex and mixed scheduling semantics. Ideally you want well defined scheduling semantics to perform a formal timing analysis.

  2. Callbacks may suffer from priority inversion. Higher priority callbacks may be blocked by lower priority callbacks.

  3. No explicit control over the callbacks execution order.

  4. No built-in control over triggering for specific topics.

Additionally, the executor overhead in terms of CPU and memory usage is
considerable. The Static Single-Threaded Executor reduces this overhead
greatly but it might not be enough for some applications.

These issues have been partially addressed by the following developments:

  * [ rclcpp WaitSet ](https://github.com/ros2/rclcpp/blob/foxy/rclcpp/include/rclcpp/wait_set.hpp) : The ` WaitSet  ` class of rclcpp allows waiting directly on subscriptions, timers, service servers, action servers, etc. instead of using an Executor. It can be used to implement deterministic, user-defined processing sequences, possibly processing multiple messages from different subscriptions together. The [ examples_rclcpp_wait_set package ](https://github.com/ros2/examples/tree/foxy/rclcpp/wait_set) provides several examples for the use of this user-level wait set mechanism.

  * [ rclc Executor ](https://github.com/ros2/rclc/blob/master/rclc/include/rclc/executor.h) : This Executor from the C Client Library _rclc_ , developed for micro-ROS, gives the user fine-grained control over the execution order of callbacks and allows for custom trigger conditions to activate callbacks. Furthermore, it implements ideas of the Logical Execution Time (LET) semantics.


Hi if i have to run heavy cron jobs on a server and every minute i can run
heavy memory consuming processes inside that cron as concurrent processes,
what do you suggest would opening a new worker thread solve my issue since i
believe i am running in Javascript out of heap memory violation when running
10 heavy processes under promise.all while when i run a single process it
seems to work fine.


[ January 14, 2021 at 5:48 pm  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-4935)


    const {
      Worker,
      isMainThread,
      workerData,
      parentPort,
    } = require("worker_threads");
    const crypto = require("crypto");

    if (isMainThread) {
      function runService() {
        return new Promise((resolve, reject) => {
          const worker = new Worker(__filename, { workerData: "world" });
          worker.on("message", resolve);
          worker.on("error", reject);
          worker.on("exit", (code) => {
            if (code !== 0)
              reject(new Error(`Worker stopped with exit code ${code}`));
          });
        });
      }

      async function run() {
        const result = await runService("world");
        console.log(result);
      }

      run().catch((err) => console.error(err));
      console.log("I should run immediately");
    } else {
      const codes = [];
      for (let i = 0; i < 5000; i++) {
        const val = doHeavyStuff(`${workerData}-${i + 1}`);
        codes.push(val);
      }

      function doHeavyStuff(item) {
        return crypto
          .createHmac("sha256", "secret")


` worker_threads ` is an exciting and useful module if you need to do CPU-
intensive tasks in your Node.js application. They provide the same behavior as
threads without sharing memory and, thus, avoid the potential race conditions
threads introduce.


  Executors  ï

Table of Contents

  * Overview

  * Basic use

  * Types of Executors

  * Callback groups

  * Scheduling semantics

  * Outlook

  * Further information


The _Multi-Threaded Executor_ creates a configurable number of threads to
allow for processing multiple messages or events in parallel. The _Static
Single-Threaded Executor_ optimizes the runtime costs for scanning the
structure of a node in terms of subscriptions, timers, service servers, action
servers, etc. It performs this scan only once when the node is added, while
the other two executors regularly scan for such changes. Therefore, the Static
Single-Threaded Executor should be used only with nodes that create all
subscriptions, timers, etc. during initialization.

All three executors can be used with multiple nodes by calling ` add_node(..)
` for each node.

    rclcpp::Node::SharedPtr node1 = ...
    rclcpp::Node::SharedPtr node2 = ...
    rclcpp::Node::SharedPtr node3 = ...
    rclcpp::executors::StaticSingleThreadedExecutor executor;
    executor.add_node(node1);
    executor.add_node(node2);
    executor.add_node(node3);
    executor.spin();

In the above example, the one thread of a Static Single-Threaded Executor is
used to serve three nodes together. In case of a Multi-Threaded Executor, the
actual parallelism depends on the callback groups.


Phenix's AvatarJoin Date
Sep 2002
Location
Near A Cube
Posts
228
Resolved Multithreading, Callbacks and Synchronization [RESOLVED]
If I have a callback function monitoring a particular window message (like say WM_PAINT), and the callback function starts an image processing function that takes longer to complete than the frequency of received WM_PAINT messages, won't the image processing routine be called sequentially at a delayed rate (due to a growing queue to call the image processing function), yet still know/retain the (real) time of the WM_PAINT message?


Follow


        * [ Python migration guide from ROS 1 ](../The-ROS2-Project/Contributing/Migration-Guide-Python.html)
      * [ ROS Build Farms ](../The-ROS2-Project/Contributing/Build-Farms.html)
      * [ Windows Tips and Tricks ](../The-ROS2-Project/Contributing/Windows-Tips-and-Tricks.html)
      * [ Contributing to ROS 2 Documentation ](../The-ROS2-Project/Contributing/Contributing-To-ROS-2-Documentation.html)
    * [ Features Status ](../The-ROS2-Project/Features.html)
    * [ Feature Ideas ](../The-ROS2-Project/Feature-Ideas.html)
    * [ Roadmap ](../The-ROS2-Project/Roadmap.html)
    * [ ROSCon Talks ](../The-ROS2-Project/ROSCon-Content.html)
    * [ Project Governance ](../The-ROS2-Project/Governance.html)
      * [ ROS 2 Technical Steering Committee Charter ](../The-ROS2-Project/Governance/ROS2-TSC-Charter.html)
      * [ ROS 2 TSC applicant intake process ](../The-ROS2-Project/Governance/ROS2-TSC-Intake-process.html)
      * [ How to Start a Community Working Group ](../The-ROS2-Project/Governance/How-To-Start-A-Community-Working-Group.html)
    * [ Marketing ](../The-ROS2-Project/Marketing.html)
  * [ Related Projects ](../Related-Projects.html)
    * [ Intel ROS 2 Projects ](../Related-Projects/Intel-ROS2-Projects.html)
    * [ NVIDIA ROS 2 Projects ](../Related-Projects/Nvidia-ROS2-Projects.html)
  * [ Glossary ](../Glossary.html)
  * [ Citations ](../Citations.html)

__ [ ROS 2 Documentation: Foxy ](../index.html)

  * [ ](../index.html)
  * [ Concepts ](../Concepts.html)
  * Executors
  * [ Edit on GitHub ](https://github.com/ros2/ros2_documentation/blob/foxy/source/Concepts/About-Executors.rst)

* * *

**You're reading the documentation for a version of ROS 2 that has reached its
EOL (end-of-life), and is no longer officially supported. If you want up-to-
date information, please have a look at[ Iron ](../../iron/index.html) . **


Site Logo
Terms of Service | About Us | Privacy Notice | Contact Us | Advertise | California - Do Not Sell My Info
Copyright 2024 TechnologyAdvice. All Rights Reserved.
Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.


##  1 answer


[ ![How To Build A Custom Gpt: Step By Step
Tutorial](https://blog.logrocket.com/wp-content/uploads/2024/04/Build-custom-
GPT-tutorial-step-by-step-tutorial-nocdn.png?w=420)
](https://blog.logrocket.com/build-custom-gpt-tutorial/) [


Amazon.com reviewer
This is the internals document you won't find on MSDN. ... Thank you Mr. Richter, and Microsoft should thank you. Were it not for this book I would have abandoned Microsoft for a much more expensive technology.
Circa 1995
Engineer - I think we should put our website address on our paper catalogs.
Vice President - Don't get too excited about this internet thing.


Let’s use [ the Worker Farm library ](https://www.npmjs.com/package/worker-
farm) to help us out instead. This tool helps efficiently distribute
processing tasks across multiple child processes, like so:


I was thinking of using threads, but I posted this topic to find out if the CallBack actually saves me from coding threads from scratch. Now I'm thinking that if I put the CallNextHookEx right after my BitBlt instead of as the last call in my GetMsgProc, and then perform the image processing after CallNextHookEx, then I may actually have built-in threading.
MSDN
The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain. A hook procedure can call this function either before or after processing the hook information.
My question now is:
Is each call to the CallBack function basically a separate thread of execution that can have more than 1 "instance" running multithreaded? Said another way, can 1 "instance" of the CallBack function still be running when another "instance" of the CallBack function begins to execute?


  Scheduling semantics  ï

If the processing time of the callbacks is shorter than the period with which
messages and events occur, the Executor basically processes them in FIFO
order. However, if the processing time of some callbacks is longer, messages
and events will be queued on the lower layers of the stack. The wait set
mechanism reports only very little information about these queues to the
Executor. In detail, it only reports whether there are any messages for a
certain topic or not. The Executor uses this information to process the
messages (including services and actions) in a round-robin fashion - but not
in FIFO order. The following flow diagram visualizes this scheduling
semantics.

![../_images/executors_scheduling_semantics.png](../_images/executors_scheduling_semantics.png)

This semantics was first described in a [ paper by Casini et al. at ECRTS 2019
](https://drops.dagstuhl.de/opus/volltexte/2019/10743/pdf/LIPIcs-
ECRTS-2019-6.pdf) . (Note: The paper also explains that timer events are
prioritized over all other messages. [ This prioritization was removed in
Eloquent. ](https://github.com/ros2/rclcpp/pull/841) )


I don’t recall that class’s implementation (I used it, but 20 years ago).
But there is NO interlocked find, there is only synchronized find.


[ August 29, 2020 at 4:01 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-3568)


  * [ Click to share on Twitter (Opens in new window)  ](https://blog.logrocket.com/multithreading-node-js-worker-threads/?share=twitter "Click to share on Twitter")
  * [ Click to share on Reddit (Opens in new window)  ](https://blog.logrocket.com/multithreading-node-js-worker-threads/?share=reddit "Click to share on Reddit")
  * [ Click to share on LinkedIn (Opens in new window)  ](https://blog.logrocket.com/multithreading-node-js-worker-threads/?share=linkedin "Click to share on LinkedIn")
  * [ Click to share on Facebook (Opens in new window)  ](https://blog.logrocket.com/multithreading-node-js-worker-threads/?share=facebook "Click to share on Facebook")
  *


"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen


So, ` setImmediate() ` is sufficient for some simple use cases, but it’s far
from an ideal solution. Can we do parallel processing without threads? Yes!


[ Traincascade with MultiThreading (TBB) -- Opencv-2.4.5
](/question/16030/traincascade-with-multithreading-tbb-opencv-245/)


Thanks for letting us know. We’ll look into having their post removed.


[ How to run slow video processing algorithms in background while showing
camera output? ](/question/2824/how-to-run-slow-video-processing-algorithms-
in-background-while-showing-camera-output/)


#  Multithreading in Node.js with worker threads


####  Jest adoption guide: Overview, examples, and alternatives


Click Here to Expand Forum to Full Width


[ ![LogRocket blog logo](https://blog.logrocket.com/wp-
content/themes/logrocket/assets/logrocket-logo.png) ](https://logrocket.com)


[ subscribe to rss feed ](/feeds/question/210946/ "subscribe to the rss feed")


[ Dejan_Maksimovic  ](https://community.osr.com/u/Dejan_Maksimovic) February
5, 2023, 7:47pm  2


While performing these operations, you want to ensure you apply as much care
as possible to avoid some of the side effects of using worker threads in
Node.js. For example, one common side effect is having race conditions.
Another is the overhead of creating new workers.


4. ![](https://secure.gravatar.com/avatar/f0a1f1511eb20f856763e2b5d4b41ee5?s=36&d=mm&r=g) **Turab Qureshi** says:


[ faq ](/faq/) [ tags ](/tags/) [ users ](/users/) [ badges ](/badges/)


  * [ Start Monitoring for Free ](https://lp.logrocket.com/blg/signup)
  * [ Sign In ](https://app.logrocket.com/)


Last updated: **Mar 30 '19**


Let’s see how we can refactor some code from our previous example to take
advantage of this. Imagine we have a large array that we want to process, and
every item in the array requires CPU-intensive processing:


[ July 27, 2022 at 5:33 pm  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-28874)


[ Dejan_Maksimovic  ](https://community.osr.com/u/Dejan_Maksimovic) February
6, 2023, 8:44am  5


If you’re interested in trying this out, see our other [ post exploring the
Partytown library ](https://blog.logrocket.com/using-web-workers-boost-third-
party-script-performance/) . You can also [ check out their documentation
](https://github.com/BuilderIO/partytown) for a more in-depth discussion.


-Receive WM_PAINT; do the blit.
-Push whatever data you need onto a shared queue with timestamp attached.
-Signal your previously created worker thread that there's an image to be processed, via a condition variable.
-Worker thread just sits in an infinite loop on a condition variable wait, so it wakes when there's work.
-When the worker thread empties the shared work queue, it waits on the condvar until there's more work.


Although this works, as you can see, the code gets more complicated. In
addition, in real-world scenarios, the algorithm is often a lot more complex
than this, so it’s hard to know where to put the ` setImmediate() ` to find a
good balance.


CornedBee said,
Actually, the Windows message model should make it impossible for a WM_PAINT to be queue while another one is not yet processed.


add a comment


opencv's gui functions, like ` namedWindow, imshow, waitKey ` HAVE to stay on
the main thread.


Phenix's AvatarJoin Date
Sep 2002
Location
Near A Cube
Posts
228
Re: Multithreading, Callbacks and Synchronization
CornedBee
Actually, the Windows message model should made it impossible for a WM_PAINT to be queue while another one is not yet processed.
I'm not trying to discuss how MS Windows should have been written, I'm just trying to deal with how it is written. As WM_PAINT is a posted message, more than 1 may be in the queue.
MSDN
The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
CornedBee
And all logic, of course, says that a program that receives paint messages faster than it can handle them is pretty broken.
I'll need you to explain how this is at all relevant in light of how MS Windows handles WM_PAINT (i.e. posted) messages. Enough MS Windows bashing.


And all logic, of course, says that a program that receives paint messages faster than it can handle them is pretty broken.


Reply


7. ![](https://secure.gravatar.com/avatar/57b0e43267f2b6c75174d1b5519457e4?s=36&d=mm&r=g) **venkat** says:


[ ![](https://blog.logrocket.com/wp-content/uploads/2021/05/nitish-
sharma.jpeg?w=150&h=150&crop=1)
](https://blog.logrocket.com/author/nitishsharma/) [ Nitish Sharma
](https://blog.logrocket.com/author/nitishsharma/)


  * **Creating a pool of workers** : This mechanism can help you efficiently manage and reuse a pool of worker threads to perform concurrent and parallel tasks. Rather than creating and terminating worker threads for each task, you can reuse threads with the help of a pool, which can in turn improve performance. You can use a [ library like workerpool ](https://www.npmjs.com/package/workerpool) to create and manage a pool of workers for your app
  * **Handling shutdown** : Ensure proper shutdown and cleanup of worker threads when they are no longer in use. In the case of threads in a worker pool, you don’t have to worry about shutting them down, as each thread would be released back to the pool to make it available for a new task. Other than that, you can use the ` exit ` event to shut down a worker thread that is no longer in use
  * **Passing data** : Ensure that your worker and main thread do not share the same state, as this may cause race conditions. Passing data is recommended over sharing state because each worker thread has its own context and runs independently of the main thread
  * **Performance evaluation** : Evaluate the performance implications of using worker threads for your specific use case. For example, in cases where you intend to perform I/O-bound tasks, using workers may not be the best fit for you


[ December 31, 2019 at 3:26 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-1237)


I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu) for 386(486) AT clones. ... and it probably never will support anything other than AT-harddisks, as that's all I have :-(.
-Linus


Worker threads and web workers serve similar purposes but have some
differences due to the distinct environments in which they operate:


![](https://blog.logrocket.com/wp-content/uploads/2022/06/footer-cta-dots-
left.png) ![](https://blog.logrocket.com/wp-content/uploads/2022/06/footer-
cta-dots-right.png)


How to update cv::namedwindow in multi-threading environment?


Apr 12, 2024 ⋅ 12 min read


edit


Question: What documentation, if any, defines the concurrency rules for when
callback functions are called to deliver the notification of image load events
and thread create/delete events?


](https://blog.logrocket.com/building-web-based-terminal-components-termino-
js/)


Outstanding article, It was so easy to understand a topic that I thought was
complicated.


[ JeyP4 ](/users/408655/jeyp4/)
64  ●  1  ●  6


[ May 4, 2023 at 12:02 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-35315)


###  Introducing: Partytown


Here, we need two things: the ` workerData ` that the main app sent to us and
a way to return information to the main app. This is done with the `
parentPort ` , which has a ` postMessage ` method where we will pass the
result of our processing.


Worker threads are designed for parallelizing CPU-bound tasks. As mentioned
earlier, worker threads work in isolated contexts and therefore have no effect
on the main thread.


####  Building web-based terminal components with Termino.js


Let’s see why and how to build custom GPTs — personalized versions of ChatGPT
that act as custom chatbots to serve a specific purpose.


Reply


3. ![](https://secure.gravatar.com/avatar/1170401748b20bed2e3e75476194ed56?s=36&d=mm&r=g) **[ baraa ](https://baraabytes.com) ** says:


There are multithreading methods other than worker threads that may be better
for specific use cases. These include thread pools for I/O-bound tasks, child
processes, and clustering. Let’s see how each one works and what their pros
and cons are:


  * _Reentrant:_ Callbacks of this group may be executed in parallel.

Callbacks of different callback groups may always be executed in parallel. The
Multi-Threaded Executor uses its threads as a pool to process as many
callbacks as possible in parallel according to these conditions. For tips on
how to use callback groups efficiently, see [ Using Callback Groups  ](../How-
To-Guides/Using-callback-groups.html) .

Since Galactic, the interface of the Executor base class in rclcpp has been
refined by a new function ` add_callback_group(..)  ` . This allows
distributing callback groups to different Executors. By configuring the
underlying threads using the operating system scheduler, specific callbacks
can be prioritized over other callbacks. For example, the subscriptions and
timers of a control loop can be prioritized over all other subscriptions and
standard services of a node. The [ examples_rclcpp_cbg_executor package
](https://github.com/ros2/examples/tree/foxy/rclcpp/executors/cbg_executor)
provides a demo of this mechanism.


Join Date
Dec 2003
Posts
703
Re: Multithreading, Callbacks and Synchronization
I think you rather misunderstood CB's post. Anyway, the answer to your question is no. Callbacks have nothing inherently to do with multithreading; the functions will be called synchronously.


[ chuckchopp  ](https://community.osr.com/u/chuckchopp) February 5, 2023,
6:52pm  1


[ edit ](/questions/210946/edit/) [ retag ](/s/questions/210946/retag/) flag
offensive  [ close ](/questions/210946/close/) merge  delete


[ August 5, 2022 at 4:42 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-29167)


I intend to make a change to introduce additional synchronization within the
callback function to ensure that this is no longer a problem.


[ June 25, 2020 at 11:59 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-2945)


    const arr = [/*large array*/]
    for (const item of arr) {
      // do heavy stuff for each item on the array
    }
    // code that runs after the whole array is executed


"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen


10. ![](https://secure.gravatar.com/avatar/53e196cf2c57dfd3015af4464151b50b?s=36&d=mm&r=g) **Basit** says:


Perfect article. Complete and easylly understandable


* [ Multithreading ](/questions/scope:all/sort:activity-desc/tags:Multithreading/page:1/)


Very helpful! Thanks


  * Introduces additional processes, leading to increased resource overhead
  * Communication between processes involves serialization and deserialization, potentially impacting performance


It’s obvious that a process create/delete event should only ever get delivered
a single time for a given process and cannot, by definition, both be delivered
concurrently for the same process by different threads.


and be careful with multithreading in general. most of opencv's functionality
is NOT THREADSAFE by design !


[ ![ gravatar image]() ]() [ ]() (  2024-04-14 12:57:56 -0600  )  edit


#  [ Concurrent delivery of image load events via
PsSetLoadImageNotifyRoutine() and a callback function. ](/t/concurrent-
delivery-of-image-load-events-via-pssetloadimagenotifyroutine-and-a-callback-
function/58070)


* [ ros ](/questions/scope:all/sort:activity-desc/tags:ros/page:1/)


##  The naive solution: Synchronous code-splitting


middleware until it is taken for processing by a callback function. (This is a
crucial difference to ROS 1.) A _wait set_ is used to inform the Executor
about available messages on the middleware layer, with one binary flag per
queue. The _wait set_ is also used to detect when timers expire.

![../_images/executors_basic_principle.png](../_images/executors_basic_principle.png)

The Single-Threaded Executor is also used by the container process for [
components  ](About-Composition.html) , i.e. in all cases where nodes are
created and executed without an explicit main function.


Very Nice artice ! Congratulations!!


    const {
      Worker,
      isMainThread,
      workerData,
      parentPort,
    } = require("worker_threads");
    const sharp = require("sharp");

    if (isMainThread) {
      function runService() {
        return new Promise((resolve, reject) => {
          const worker = new Worker(__filename, {
            workerData: {
              imagePath: "input.jpeg",
              outputPath: "output.jpeg",
              width: 24000,
              height: 16000,
            },
          });
          worker.on("message", resolve);
          worker.on("error", reject);
          worker.on("exit", (code) => {
            if (code !== 0)
              reject(new Error(`Worker stopped with exit code ${code}`));
          });
        });
      }

      async function run() {
        const result = await runService("world");
        console.log(result);
      }

      run().catch((err) => console.error(err));
      console.log("Resizing image");
    } else {
      const { imagePath, outputPath, width, height } = workerData;


[ ROS 2 Documentation: Foxy ![Logo](../_static/foxy-small.png)
](../index.html)

  * [ Installation ](../Installation.html)
    * [ Ubuntu (Debian) ](../Installation/Ubuntu-Install-Debians.html)
    * [ Windows (binary) ](../Installation/Windows-Install-Binary.html)
    * [ Alternatives ](../Installation/Alternatives.html)
      * [ Ubuntu (source) ](../Installation/Alternatives/Ubuntu-Development-Setup.html)
      * [ Ubuntu (binary) ](../Installation/Alternatives/Ubuntu-Install-Binary.html)
      * [ Windows (source) ](../Installation/Alternatives/Windows-Development-Setup.html)
      * [ macOS (source) ](../Installation/Alternatives/macOS-Development-Setup.html)
      * [ macOS (binary) ](../Installation/Alternatives/macOS-Install-Binary.html)
      * [ Fedora (source) ](../Installation/Alternatives/Fedora-Development-Setup.html)
      * [ Latest development (source) ](../Installation/Alternatives/Latest-Development-Setup.html)
    * [ Maintain source checkout ](../Installation/Maintaining-a-Source-Checkout.html)
    * [ Testing with pre-release binaries ](../Installation/Testing.html)
    * [ DDS implementations ](../Installation/DDS-Implementations.html)
      * [ Connext security plugins ](../Installation/DDS-Implementations/Install-Connext-Security-Plugins.html)
      * [ RTI Connext DDS ](../Installation/DDS-Implementations/Install-Connext-University-Eval.html)
      * [ Eclipse Cyclone DDS ](../Installation/DDS-Implementations/Working-with-Eclipse-CycloneDDS.html)
      * [ GurumNetworks GurumDDS ](../Installation/DDS-Implementations/Working-with-GurumNetworks-GurumDDS.html)
      * [ eProsima Fast DDS ](../Installation/DDS-Implementations/Working-with-eProsima-Fast-DDS.html)
  * [ Distributions ](../Releases.html)
    * [ Iron Irwini ( ` iron  ` ) ](../Releases/Release-Iron-Irwini.html)
      * [ Iron Irwini Changelog ](../Releases/Iron-Irwini-Complete-Changelog.html)
    * [ Humble Hawksbill ( ` humble  ` ) ](../Releases/Release-Humble-Hawksbill.html)
      * [ Humble Hawksbill changelog ](../Releases/Humble-Hawksbill-Complete-Changelog.html)
    * [ Rolling Ridley ( ` rolling  ` ) ](../Releases/Release-Rolling-Ridley.html)
    * [ Development Distribution ](../Releases/Development.html)
      * [ Jazzy Jalisco (codename âjazzyâ; May, 2024) ](../Releases/Release-Jazzy-Jalisco.html)
    * [ End-of-Life Distributions ](../Releases/End-of-Life.html)
      * [ Galactic Geochelone ( ` galactic  ` ) ](../Releases/Release-Galactic-Geochelone.html)
        * [ Galactic Geochelone changelog ](../Releases/Galactic-Geochelone-Complete-Changelog.html)
      * [ Foxy Fitzroy ( ` foxy  ` ) ](../Releases/Release-Foxy-Fitzroy.html)
      * [ Eloquent Elusor ( ` eloquent  ` ) ](../Releases/Release-Eloquent-Elusor.html)
      * [ Dashing Diademata ( ` dashing  ` ) ](../Releases/Release-Dashing-Diademata.html)
      * [ Crystal Clemmys ( ` crystal  ` ) ](../Releases/Release-Crystal-Clemmys.html)
      * [ Bouncy Bolson ( ` bouncy  ` ) ](../Releases/Release-Bouncy-Bolson.html)
      * [ Ardent Apalone ( ` ardent  ` ) ](../Releases/Release-Ardent-Apalone.html)
      * [ Beta 3 ( ` r2b3  ` ) ](../Releases/Beta3-Overview.html)


* Not suitable for tasks that are CPU-bound


A common example of CPU-intensive task is image resizing. Let’s take a look at
that with [ the sharp library ](https://github.com/lovell/sharp) , which
provides a high-speed module for image processing in Node:


[ May 9, 2023 at 8:30 am  ](https://blog.logrocket.com/multithreading-node-js-
worker-threads/#comment-35383)


Introducing Galileo AI


[ May 1, 2020 at 5:49 am  ](https://blog.logrocket.com/multithreading-node-js-
worker-threads/#comment-2295)


![LogRocket Galileo logo](https://blog.logrocket.com/wp-
content/uploads/2023/12/GalileoAIPreview.png)


[ Alberto Gimeno ](https://blog.logrocket.com/author/albertogimeno/) Ecosystem
Engineer at GitHub. Sometimes I write about JavaScript, Node.js, and frontend
development.


Reply


Web workers can also be used to run third-party scripts.


Asked: ** 2019-03-30 04:49:03 -0600  **


[ View all posts ](https://blog.logrocket.com/)


[ chuckchopp  ](https://community.osr.com/u/chuckchopp) February 5, 2023,
11:34pm  4


As you can see, this is as easy as passing the filename as an argument and the
data we want the worker to process. Remember that this data is cloned and is
not in any shared memory.


    * [ Visualizing ROS 2 data with Foxglove Studio ](../How-To-Guides/Visualizing-ROS-2-Data-With-Foxglove-Studio.html)
    * [ ROS 2 Package Maintainer Guide ](../How-To-Guides/Package-maintainer-guide.html)
    * [ Building a custom Debian package ](../How-To-Guides/Building-a-Custom-Debian-Package.html)
    * [ Building ROS 2 with tracing instrumentation ](../How-To-Guides/Building-ROS-2-with-Tracing-Instrumentation.html)
    * [ Topics vs Services vs Actions ](../How-To-Guides/Topics-Services-Actions.html)
    * [ Using variants ](../How-To-Guides/Using-Variants.html)
    * [ Using the ` ros2  param  ` command-line tool ](../How-To-Guides/Using-ros2-param.html)
    * [ ROS 2 on Raspberry Pi ](../How-To-Guides/Installing-on-Raspberry-Pi.html)
    * [ Using Callback Groups ](../How-To-Guides/Using-callback-groups.html)
    * [ Setup ROS 2 with VSCode and Docker [community-contributed] ](../How-To-Guides/Setup-ROS-2-with-VSCode-and-Docker-Container.html)
    * [ Building RQt from source ](../How-To-Guides/RQt-Source-Install.html)
      * [ Building RQt from source on macOS ](../How-To-Guides/RQt-Source-Install-MacOS.html)
      * [ Building RQt from source on Windows 10 ](../How-To-Guides/RQt-Source-Install-Windows10.html)
  * [ Concepts ](../Concepts.html)
    * [ The ROS_DOMAIN_ID ](About-Domain-ID.html)
    * [ About different ROS 2 DDS/RTPS vendors ](About-Different-Middleware-Vendors.html)
    * [ About logging and logger configuration ](About-Logging.html)
    * [ About Quality of Service settings ](About-Quality-of-Service-Settings.html)
    * [ About ROS 2 client libraries ](About-ROS-2-Client-Libraries.html)
    * [ About ROS 2 interfaces ](About-ROS-Interfaces.html)
    * [ About parameters in ROS 2 ](About-ROS-2-Parameters.html)
    * Executors
    * [ About topic statistics ](About-Topic-Statistics.html)
    * [ Introspection with command line tools ](About-Command-Line-Tools.html)
    * [ Overview and usage of RQt ](About-RQt.html)
    * [ About Composition ](About-Composition.html)
    * [ On the mixing of ament and catkin (catment) ](About-Catment.html)
    * [ About Cross-compilation ](About-Cross-Compilation.html)
    * [ About tf2 ](About-Tf2.html)
    * [ About the build system ](About-Build-System.html)
    * [ About internal ROS 2 interfaces ](About-Internal-Interfaces.html)
    * [ About ROS 2 middleware implementations ](About-Middleware-Implementations.html)
    * [ About ROS 2 client libraries ](About-ROS-2-Client-Libraries.html)
  * [ Contact ](../Contact.html)
  * [ The ROS 2 Project ](../The-ROS2-Project.html)
    * [ Contributing ](../The-ROS2-Project/Contributing.html)
      * [ ROS 2 developer guide ](../The-ROS2-Project/Contributing/Developer-Guide.html)
      * [ Code style and language versions ](../The-ROS2-Project/Contributing/Code-Style-Language-Versions.html)
      * [ Quality guide: ensuring code quality ](../The-ROS2-Project/Contributing/Quality-Guide.html)
      * [ Migration guide from ROS 1 ](../The-ROS2-Project/Contributing/Migration-Guide.html)


[ ![Building Web-Based Terminal Components With
Termino.js](https://blog.logrocket.com/wp-content/uploads/2024/04/building-
web-based-terminal-components-termino-js.png?w=420)
](https://blog.logrocket.com/building-web-based-terminal-components-termino-
js/) [


[ __ Documentation ](https://docs.opencv.org)


First time here? Check out the FAQ!


##  What are worker threads?


VBForums - Visual Basic and VB .NET Discussions and More!
Forum
New PostsFAQCalendarForum ActionsQuick Links
What's New?
Advertiser Disclosure
Submit
Advanced Search
HomeVBForumsOther LanguagesC and C++Multithreading, Callbacks and Synchronization [RESOLVED]
If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.
Results 1 to 7 of 7
Thread: Multithreading, Callbacks and Synchronization [RESOLVED]share-icon
Thread Tools
Display
Feb 28th, 2005, 11:11 AM#1
Phenix Phenix is offline
Thread Starter
Addicted Member


* [ callbacks ](/questions/scope:all/sort:activity-desc/tags:callbacks/page:1/)


He was implying that he wan't absolutely sure of his post in using the word should not that windows is lacking. He wasn't bashing Windows at all. Although I wouldn't complain if he did...
www.ForYouAndI.com
www.WARnux.com
Reply With QuoteReply With Quote  Mar 1st, 2005, 04:55 AM#6
CornedBee CornedBee is offline
Kitten

CornedBee's AvatarJoin Date
Aug 2001
Location
In a microchip!
Posts
11,594
Re: Multithreading, Callbacks and Synchronization
I hold the maxim that users of Internet Explorer shouldn't be programmers (part of the reason why I don't mind my tutorial not being accessible with IE) but that's a completely different story.


  Basic use  ï

In the simplest case, the main thread is used for processing the incoming
messages and events of a Node by calling ` rclcpp::spin(..)  ` as follows:

    int main(int argc, char* argv[])
    {
       // Some initialization.
       rclcpp::init(argc, argv);
       ...

       // Instantiate a node.
       rclcpp::Node::SharedPtr node = ...

       // Run the executor.
       rclcpp::spin(node);

       // Shutdown and exit.
       ...
       return 0;
    }

The call to ` spin(node)  ` basically expands to an instantiation and
invocation of the Single-Threaded Executor, which is the simplest Executor:

    rclcpp::executors::SingleThreadedExecutor executor;
    executor.add_node(node);
    executor.spin();

By invoking ` spin()  ` of the Executor instance, the current thread starts
querying the rcl and middleware layers for incoming messages and other events
and calls the corresponding callback functions until the node shuts down. In
order not to counteract the QoS settings of the middleware, an incoming
message is not stored in a queue on the Client Library layer but kept in the


If you have two tasks — one that will take ` 10s ` and one that will take ` 1s
` , in that order — it’s not ideal to have to wait ` 10s ` to execute the
second task. It’s even less ideal if that task never reaches execution because
another process got in its way.


Thanks a lot for such insight. Cheers.


Two of the callbacks are documented as being called by the kernel while in a
critical region, so it’s clear that the thread executing the callback cannot
be interrupted in those cases. However, no statements are made about any kind
of serialization of the invocation of those callbacks by the kernel,
especially as it relates to notifications of a given type for the same process
or for different processes.


So, one simple thing we can do is split our code into smaller synchronous code
blocks and call ` setImmediate(callback) ` to tell Node.js we are done. This
way, it can continue executing things that are pending in the queue. In other
words, it can move on to the next iteration or “tick” of the event loop.


[ September 21, 2019 at 5:38 am  ](https://blog.logrocket.com/multithreading-
node-js-worker-threads/#comment-574)


The virtual machine and the operating system run the I/O in parallel for us.
When it’s time to send data back to our JavaScript code, it’s the JavaScript
that runs in a single thread.


[ April 2, 2022 at 10:03 am  ](https://blog.logrocket.com/multithreading-node-
js-worker-threads/#comment-20689)


Leverage services like AWS Lambda, CloudFront, and S3 to handle images more
effectively, optimizing performance and providing a better UX.


That said, I would have said this first if it had to precede what I'm telling you now. Having said that, what I'm telling you now is the same thing I just said about the annoying phrases "That said" and "Having said that".


6. ![](https://secure.gravatar.com/avatar/65868f153b77becae0a5e1d621103f0d?s=36&d=mm&r=g) **Serei Solovev** says:


[ How to build OpenCV with TBB support? ](/question/10/how-to-build-opencv-
with-tbb-support/)


Reply


Going back to our previous example, imagine we now have a query that returns a
few thousand results and we need to decrypt the values in our JavaScript code:


Jan 8, 2024 ⋅ 15 min read


Method  |  Description  |  Pros  |  Cons
---|---|---|---
[ Thread pools ](https://blog.logrocket.com/complete-guide-threads-node-
js/#implementing-worker-pool) |  A mechanism in Node.js designed to
efficiently manage I/O-bound operations. Despite the single-threaded nature of
the primary event loop in Node.js, you can delegate tasks like file system
operations, network requests, and other asynchronous I/O operations to a
separate thread pool. You can use a [ library such as libuv
](https://github.com/libuv/libuv) to achieve this.  |


[ edit ](/s/answers/210948/edit/) flag offensive  delete  [ link
](/question/210946/how-to-update-cvnamedwindow-in-multi-threading-
environment/?answer=210948#post-id-210948 "permanent link") more


  1. You may not be blocking the main app, but the forked process will only be able to process one task at a time
  2. If one task crashes the process, it will leave all tasks sent to the same process unfinished


##  What is the Web Workers API?


  * Don't miss a moment with [ The Replay ](https://lp.logrocket.com/subscribe-thereplay) , a curated newsletter from LogRocket
  * [ Learn ](https://blog.logrocket.com/rethinking-error-tracking-product-analytics/) how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  * Use React's useEffect [ to optimize your application's performance ](https://blog.logrocket.com/understanding-react-useeffect-cleanup-function/)
  * Switch between [ multiple versions of Node ](https://blog.logrocket.com/switching-between-node-versions-during-development/)
  * [ Discover ](https://blog.logrocket.com/using-react-children-prop-with-typescript/) how to use the React children prop with TypeScript
  * [ Explore ](https://blog.logrocket.com/creating-custom-mouse-cursor-css/) creating a custom mouse cursor with CSS
  * Advisory boards aren’t just for executives. [ Join LogRocket’s Content Advisory Board. ](https://lp.logrocket.com/blg/content-advisory-board-signup) You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.


Keep in mind that even though creating a worker is a lot cheaper than forking
a process, it can also use too many resources depending on your needs. In that
case, the docs [ recommend you create a pool of workers
](https://nodejs.org/api/worker_threads.html#:~:text=The%20above%20example%20spawns%20a%20Worker%20thread%20for%20each%20parseJSAsync\(\)%20call.%20In%20practice%2C%20use%20a%20pool%20of%20Workers%20for%20these%20kinds%20of%20tasks.%20Otherwise%2C%20the%20overhead%20of%20creating%20Workers%20would%20likely%20exceed%20their%20benefit.)
.


What you can do is:


          * [ Setting up a robot simulation (Advanced) ](../Tutorials/Advanced/Simulators/Webots/Setting-Up-Simulation-Webots-Advanced.html)
        * [ Ignition ](../Tutorials/Advanced/Simulators/Ignition/Simulation-Ignition.html)
          * [ Setting up a robot simulation (Ignition Gazebo) ](../Tutorials/Advanced/Simulators/Ignition/Ignition.html)
    * [ Demos ](../Tutorials/Demos.html)
      * [ Using quality-of-service settings for lossy networks ](../Tutorials/Demos/Quality-of-Service.html)
      * [ Managing nodes with managed lifecycles ](../Tutorials/Demos/Managed-Nodes.html)
      * [ Setting up efficient intra-process communication ](../Tutorials/Demos/Intra-Process-Communication.html)
      * [ Recording and playing back data with ` rosbag  ` using the ROS 1 bridge ](../Tutorials/Demos/Rosbag-with-ROS1-Bridge.html)
      * [ Understanding real-time programming ](../Tutorials/Demos/Real-Time-Programming.html)
      * [ Experimenting with a dummy robot ](../Tutorials/Demos/dummy-robot-demo.html)
      * [ Logging ](../Tutorials/Demos/Logging-and-logger-configuration.html)
    * [ Miscellaneous ](../Tutorials/Miscellaneous.html)
      * [ Packaging your ROS 2 application as a snap [community-contributed] ](../Tutorials/Miscellaneous/Packaging-your-ROS-2-application-as-a-snap.html)
      * [ Deploying on IBM Cloud Kubernetes [community-contributed] ](../Tutorials/Miscellaneous/Deploying-ROS-2-on-IBM-Cloud.html)
      * [ Using Eclipse Oxygen with ` rviz2  ` [community-contributed] ](../Tutorials/Miscellaneous/Eclipse-Oxygen-with-ROS-2-and-rviz2.html)
      * [ Building a real-time Linux kernel [community-contributed] ](../Tutorials/Miscellaneous/Building-Realtime-rt_preempt-kernel-for-ROS-2.html)
      * [ Building a package with Eclipse 2021-06 ](../Tutorials/Miscellaneous/Building-ROS2-Package-with-eclipse-2021-06.html)
  * [ How-to Guides ](../How-To-Guides.html)
    * [ Installation troubleshooting ](../How-To-Guides/Installation-Troubleshooting.html)
    * [ Developing a ROS 2 package ](../How-To-Guides/Developing-a-ROS-2-Package.html)
    * [ ament_cmake user documentation ](../How-To-Guides/Ament-CMake-Documentation.html)
    * [ ament_cmake_python user documentation ](../How-To-Guides/Ament-CMake-Python-Documentation.html)
    * [ Migrating launch files from ROS 1 to ROS 2 ](../How-To-Guides/Launch-files-migration-guide.html)
    * [ Using Python, XML, and YAML for ROS 2 Launch Files ](../How-To-Guides/Launch-file-different-formats.html)
    * [ Using ROS 2 launch to launch composable nodes ](../How-To-Guides/Launching-composable-nodes.html)
    * [ Migrating YAML parameter files from ROS 1 to ROS 2 ](../How-To-Guides/Parameters-YAML-files-migration-guide.html)
    * [ Passing ROS arguments to nodes via the command-line ](../How-To-Guides/Node-arguments.html)
    * [ Synchronous vs. asynchronous service clients ](../How-To-Guides/Sync-Vs-Async.html)
    * [ DDS tuning information ](../How-To-Guides/DDS-tuning.html)
    * [ rosbag2: Overriding QoS Policies ](../How-To-Guides/Overriding-QoS-Policies-For-Recording-And-Playback.html)
    * [ Working with multiple ROS 2 middleware implementations ](../How-To-Guides/Working-with-multiple-RMW-implementations.html)
    * [ Cross-compilation ](../How-To-Guides/Cross-compilation.html)
    * [ Releasing a Package ](../How-To-Guides/Releasing/Releasing-a-Package.html)
      * [ First Time Release ](../How-To-Guides/Releasing/First-Time-Release.html)
      * [ Subsequent Releases ](../How-To-Guides/Releasing/Subsequent-Releases.html)
      * [ Release Team / Repository ](../How-To-Guides/Releasing/Release-Team-Repository.html)
      * [ Release Track ](../How-To-Guides/Releasing/Release-Track.html)
    * [ Using Python Packages with ROS 2 ](../How-To-Guides/Using-Python-Packages.html)
    * [ Porting RQt plugins to Windows ](../How-To-Guides/RQt-Port-Plugin-Windows.html)
    * [ Running ROS 2 nodes in Docker [community-contributed] ](../How-To-Guides/Run-2-nodes-in-single-or-separate-docker-containers.html)


  * The main process can communicate with the child process by sending and receiving events
  * No memory is shared
  * All the data exchanged is “cloned,” meaning that changing it on one side doesn’t change it on the other side
  * If we don’t share memory, we don’t have race conditions, and we don’t need threads!


  Types of Executors  ï

Currently, rclcpp provides three Executor types, derived from a shared parent
class:

![digraph Flatland {

   Executor -> SingleThreadedExecutor \[dir = back, arrowtail = empty\];

   Executor -> MultiThreadedExecutor \[dir = back, arrowtail = empty\];

   Executor -> StaticSingleThreadedExecutor \[dir = back, arrowtail = empty\];

   Executor  \[shape=polygon,sides=4\];

   SingleThreadedExecutor  \[shape=polygon,sides=4\];

   MultiThreadedExecutor  \[shape=polygon,sides=4\];

   StaticSingleThreadedExecutor  \[shape=polygon,sides=4\];

   }](../_images/graphviz-c1160194dae16051e00be2abef23d0fce5e7c347.png)


[ ThatsBerkan  ](https://community.osr.com/u/ThatsBerkan) February 5, 2023,
8:07pm  3


I am sorry, but the Oracle was mistaken. You cannot help us.
-Matrix video game


[ How do I update OpenCV for ROS? [closed] ](/question/2035/how-do-i-update-
opencv-for-ros/)


It’s also worth noting that both worker threads and web workers communicate
with the main thread in almost the same way. They both use the ` postMessage `
method, although the implementation in web workers is slightly different.


  * Facilitates the parallel execution of tasks in distinct processes, making optimal use of multi-core systems
  * Supports communication between the parent and child processes through IPC mechanisms such as standard input/output, events, and messages
  * Suitable for both CPU-bound and I/O-bound tasks


After evaluating the potential performance implications of worker threads in
your Node.js project, you may decide against using workers for your specific
needs. In such cases, you can use one of the other options we’ll explore in
the next section.


![Multithreading In Node Js With Worker
Threads](https://blog.logrocket.com/wp-content/uploads/2024/01/Multithreading-
Node-js-worker-threads.png)


Martin,
That would still leave you limited to the amount of work the main thread can
do. Everything will just run slower. I would not recommend this approach.
With worker threads, the program gets access to a new CPU core where new work
can be done.
Niels


The system might have been compromised, in my opinion. As Dejan_Maksimovic
suggested, you can just use a synchronization object as a workaround for now,
before modifying the linked list.


        * [ Using event handlers ](../Tutorials/Intermediate/Launch/Using-Event-Handlers.html)
        * [ Managing large projects ](../Tutorials/Intermediate/Launch/Using-ROS2-Launch-For-Large-Projects.html)
      * [ ` tf2  ` ](../Tutorials/Intermediate/Tf2/Tf2-Main.html)
        * [ Introducing ` tf2  ` ](../Tutorials/Intermediate/Tf2/Introduction-To-Tf2.html)
        * [ Writing a static broadcaster (Python) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Static-Broadcaster-Py.html)
        * [ Writing a static broadcaster (C++) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Static-Broadcaster-Cpp.html)
        * [ Writing a broadcaster (Python) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Broadcaster-Py.html)
        * [ Writing a broadcaster (C++) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Broadcaster-Cpp.html)
        * [ Writing a listener (Python) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Listener-Py.html)
        * [ Writing a listener (C++) ](../Tutorials/Intermediate/Tf2/Writing-A-Tf2-Listener-Cpp.html)
        * [ Adding a frame (Python) ](../Tutorials/Intermediate/Tf2/Adding-A-Frame-Py.html)
        * [ Adding a frame (C++) ](../Tutorials/Intermediate/Tf2/Adding-A-Frame-Cpp.html)
        * [ Using time (Python) ](../Tutorials/Intermediate/Tf2/Learning-About-Tf2-And-Time-Py.html)
        * [ Using time (C++) ](../Tutorials/Intermediate/Tf2/Learning-About-Tf2-And-Time-Cpp.html)
        * [ Traveling in time (Python) ](../Tutorials/Intermediate/Tf2/Time-Travel-With-Tf2-Py.html)
        * [ Traveling in time (C++) ](../Tutorials/Intermediate/Tf2/Time-Travel-With-Tf2-Cpp.html)
        * [ Debugging ](../Tutorials/Intermediate/Tf2/Debugging-Tf2-Problems.html)
        * [ Quaternion fundamentals ](../Tutorials/Intermediate/Tf2/Quaternion-Fundamentals.html)
        * [ Using stamped datatypes with ` tf2_ros::MessageFilter  ` ](../Tutorials/Intermediate/Tf2/Using-Stamped-Datatypes-With-Tf2-Ros-MessageFilter.html)
      * [ Testing ](../Tutorials/Intermediate/Testing/Testing-Main.html)
        * [ Running Tests in ROS 2 from the Command Line ](../Tutorials/Intermediate/Testing/CLI.html)
        * [ Writing Basic Tests with C++ with GTest ](../Tutorials/Intermediate/Testing/Cpp.html)
        * [ Writing Basic Tests with Python ](../Tutorials/Intermediate/Testing/Python.html)
      * [ URDF ](../Tutorials/Intermediate/URDF/URDF-Main.html)
        * [ Building a visual robot model from scratch ](../Tutorials/Intermediate/URDF/Building-a-Visual-Robot-Model-with-URDF-from-Scratch.html)
        * [ Building a movable robot model ](../Tutorials/Intermediate/URDF/Building-a-Movable-Robot-Model-with-URDF.html)
        * [ Adding physical and collision properties ](../Tutorials/Intermediate/URDF/Adding-Physical-and-Collision-Properties-to-a-URDF-Model.html)
        * [ Using Xacro to clean up your code ](../Tutorials/Intermediate/URDF/Using-Xacro-to-Clean-Up-a-URDF-File.html)
        * [ Using URDF with ` robot_state_publisher  ` ](../Tutorials/Intermediate/URDF/Using-URDF-with-Robot-State-Publisher.html)
    * [ Advanced ](../Tutorials/Advanced.html)
      * [ Enabling topic statistics (C++) ](../Tutorials/Advanced/Topic-Statistics-Tutorial/Topic-Statistics-Tutorial.html)
      * [ Using Fast DDS Discovery Server as discovery protocol [community-contributed] ](../Tutorials/Advanced/Discovery-Server/Discovery-Server.html)
      * [ Implementing a custom memory allocator ](../Tutorials/Advanced/Allocator-Template-Tutorial.html)
      * [ Recording a bag from a node (C++) ](../Tutorials/Advanced/Recording-A-Bag-From-Your-Own-Node-CPP.html)
      * [ Simulators ](../Tutorials/Advanced/Simulators/Simulation-Main.html)
        * [ Webots ](../Tutorials/Advanced/Simulators/Webots/Simulation-Webots.html)
          * [ Installation (Ubuntu) ](../Tutorials/Advanced/Simulators/Webots/Installation-Ubuntu.html)
          * [ Installation (Windows) ](../Tutorials/Advanced/Simulators/Webots/Installation-Windows.html)
          * [ Installation (macOS) ](../Tutorials/Advanced/Simulators/Webots/Installation-MacOS.html)
          * [ Setting up a robot simulation (Basic) ](../Tutorials/Advanced/Simulators/Webots/Setting-Up-Simulation-Webots-Basic.html)


Reply


This process might take a few seconds, and any other JavaScript execution will
be queued during that time. As a result, we might be blocking all our users
during that time if we are running a server in the same application.


[ ALL ](/questions/scope:all/sort:activity-desc/page:1/) [ UNANSWERED
](/questions/scope:unanswered/sort:answers-asc/page:1/)


####  Recent posts:


####  20 Replies to "Multithreading in Node.js with worker threads"


To fix these problems, we need multiple forks, not only one. But we need to
limit the number of forked processes because each one will have all the
virtual machine code duplicated in memory, meaning a few MBs per process and a
non-trivial boot time.


Question. Do you know that the character "?" means I'm asking a question? Question. Do you know that spoken inflection also provides the same cue? So please don't say, "Question" before you ask your question. Believe me I'll know.


[ Child processes ](https://blog.logrocket.com/node-js-child-process-launch-
external-programs/) |  Facilitated by the child_process module. They allow us
to initiate separate instances of the Node.js runtime or other executables. We
can facilitate communication between these parent and child processes through
inter-process communication (IPC).  |


![](https://blog.logrocket.com/wp-content/uploads/2022/09/logrocket-logo-
frontend-analytics.png)


Imagine that a calculation takes 10 seconds. If we are running a web server,
that means that all of the other requests get blocked for at least 10s because
of that calculation. That’s a disaster — anything more than 100ms could be too
much.


    const crypto = require('crypto')

    const arr = new Array(200).fill('something')
    function processChunk() {
      if (arr.length === 0) {
        // code that runs after the whole array is executed
      } else {
        console.log('processing chunk');
        // pick 10 items and remove them from the array
        const subarr = arr.splice(0, 10)
        for (const item of subarr) {
          // do heavy stuff for each item on the array
          doHeavyStuff(item)
        }
        // Put the function back in the queue
        setImmediate(processChunk)
      }
    }

    processChunk()

    function doHeavyStuff(item) {
      crypto.createHmac('sha256', 'secret').update(new Array(10000).fill(item).join('.')).digest('hex')
    }

    // This is just for confirming that we can continue
    // doing things
    let interval = setInterval(() => {
      console.log('tick!')
      if (arr.length === 0) clearInterval(interval)
    }, 0)


|  [ Ask Your Question ](/questions/ask/)
---|---|---|---

0


    // index.js
    // run with node --experimental-worker index.js on Node.js 10.x
    const { Worker } = require('worker_threads')

    function runService(workerData) {
      return new Promise((resolve, reject) => {
        const worker = new Worker('./service.js', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', (code) => {
          if (code !== 0)
            reject(new Error(`Worker stopped with exit code ${code}`));
        })
      })
    }

    async function run() {
      const result = await runService('world')
      console.log(result);
    }

    run().catch(err => console.error(err))


15. ![](https://i0.wp.com/pbs.twimg.com/profile_images/1112021968121970693/ncJY1ze8_normal.jpg?resize=36%2C36) **[ Martin Omander 🇺🇦 🇺🇸 🇸🇪 (@martinomander) ](https://twitter.com/martinomander) ** says:


##  Related questions


Sort by »  [ oldest  ](/question/210946/how-to-update-cvnamedwindow-in-multi-
threading-environment/?sort=oldest#sort-top) [ newest  ](/question/210946/how-
to-update-cvnamedwindow-in-multi-threading-environment/?sort=latest#sort-top)
[ most voted  ](/question/210946/how-to-update-cvnamedwindow-in-multi-
threading-environment/?sort=votes#sort-top)


You can start using the ` worker_threads ` module today if you run Node.js
v10.5.0 or newer. However, between v10.5.0–11.7.0, you need to enable the
module by using the ` --experimental-worker ` flag when invoking Node.js.


From the example above, we had to separate the worker thread from the main
thread, making it possible to use both in the same file while still avoiding
shared memory. You want to make sure you do so in different blocks — you can
use the ` isMainThread ` variable to do that:


Given all of the above, what happens if we need to do synchronous-intense
stuff, such as making complex calculations in memory in a large dataset? Then
we might have a synchronous block of code that takes a lot of time and will
block the rest of the code.


  Callback groups  ï

ROS 2 allows organizing the callbacks of a node in groups. In rclcpp, such a
_callback group_ can be created by the ` create_callback_group  ` function of
the Node class. In rclpy, the same is done by calling the constructor of the
specific callback group type. The callback group must be stored throughout
execution of the node (eg. as a class member), or otherwise the executor
wonât be able to trigger the callbacks. Then, this callback group can be
specified when creating a subscription, timer, etc. - for example by the
subscription options:

C++  Python

    my_callback_group = create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);

    rclcpp::SubscriptionOptions options;
    options.callback_group = my_callback_group;

    my_subscription = create_subscription<Int32>("/topic", rclcpp::SensorDataQoS(),
                                                 callback, options);

    my_callback_group = MutuallyExclusiveCallbackGroup()
    my_subscription = self.create_subscription(Int32, "/topic", self.callback, qos_profile=1,
                                               callback_group=my_callback_group)

All subscriptions, timers, etc. that are created without the indication of a
callback group are assigned to the _default callback group_ . The default
callback group can be queried via `
NodeBaseInterface::get_default_callback_group()  ` in rclcpp and by `
Node.default_callback_group  ` in rclpy.

There are two types of callback groups, where the type has to be specified at
instantiation time:

  * _Mutually exclusive:_ Callbacks of this group must not be executed in parallel.


    const { workerData, parentPort } = require('worker_threads')

    // You can do any heavy stuff here, in a synchronous way
    // without blocking the "main thread"
    parentPort.postMessage({ hello: workerData })


Reply


  * [ The history of single-threaded JavaScript ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#history-single-threaded-javascript)
  * [ Is Node.js single-threaded or multithreaded? ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#node-js-single-threaded-multithreaded)
  * [ The need for threads to perform CPU-intensive tasks ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#need-threads-perform-cpu-intensive-tasks)
  * [ Why we will never have multithreading in JavaScript ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#why-never-have-multithreading-javascript)
  * [ The naive solution: Synchronous code-splitting ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#naive-solution-synchronous-code-splitting)
  * [ Running parallel processes in the background, without threads ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#running-parallel-processes-background-without-threads)
  * [ Using ` worker-farm ` to pool threads ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#using-worker-farm-pool-threads)
  * [ What are worker threads? ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#what-are-worker-threads)
    * [ Using worker threads for multiple tasks ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#using-worker-threads-multiple-tasks)
    * [ Best practices while using worker threads for CPU-intensive tasks ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#best-practices-using-worker-threads-cpu-intensive-tasks)
  * [ Multithreading alternatives to worker threads ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#multithreading-alternatives-worker-threads)
  * [ What is the Web Workers API? ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#what-is-web-workers-api)
    * [ Web workers vs. worker threads ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#web-workers-vs-worker-threads)
    * [ Introducing: Partytown ](https://blog.logrocket.com/multithreading-node-js-worker-threads/#introducing-partytown)


[ ![Using Aws Lambda And Aws Cloudfront To Optimize Image
Handling](https://blog.logrocket.com/wp-content/uploads/2024/04/Optimizing-
image-handling-AWS-Lambda-CloudFront.png?w=420)
](https://blog.logrocket.com/using-aws-lambda-cloudfront-optimize-image-
handling/) [


I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu) for 386(486) AT clones. ... and it probably never will support anything other than AT-harddisks, as that's all I have :-(.
-Linus


Jeffrey Richter wrote the book "Application Programming with Microsoft Windows". Truly wonderful. He has this to say about how GetMessage works:
Every thread has a message structure. This contains the message post queue, the message send queue, and a queue state bit field. GetMessage performs these steps:
1) If the QS_SENDMESSAGE flag is set, that is, if the send queue contains messages, they are handled.
2) If the post queue contains any messages, the first one is fetched and returned.
3) Otherwise, if the QS_QUIT flag is set (that is, if PostQuitMessage was called), a WM_QUIT is generated and returned.
4) Otherwise, if the QS_INPUT flag is set (that is, if any hardware input such as keyboard or mouse events is waiting), an appropriate message is generated.
5) Otherwise, if the QS_PAINT flag is set (that is, a window needs repainting), a WM_PAINT is generated and returned.
6) Otherwise, if the QS_TIMER flag is set (that is, a timer has ticked), a WM_TIMER is generated and returned.


Using the image processing approach, my app will hook to see another app's WM_PAINT message. At this time, it will need to BitBlt a small portion of the screen (to capture what was painted at this time). The BitBlt will happen faster than the frequency of WM_PAINT messages. At some point after BitBlt, I need to perform image processing to extract the text. But I would like to allow for the possibility of the WM_PAINT messages occurring faster than the image processing. The image processing can take as long as is needed to complete as long as the image being processed has the correct time stamp at the time the image was acquired.


In the example above, we used the ` doHeavyStuff ` function we used earlier to
perform a heavy task. It takes some milliseconds to run depending on your
system, but no matter how long it takes, the console message ` I should run
immediately ` would always run immediately.


This is the best node.js article I’ve read this year! Thanks a bunch!


The driver has a callback function registered via
PsSetLoadImageNotifyRoutine(), and the callback function gets called by the
kernel for each image load event that happens for a process. That has been
working fine for 15+ years.


What we need is some kind of background processing, a way of running a task
with input that could use whatever amount of CPU and time it needs to return a
result back to the main application. Something like this:


Hey there, want to help make our blog better?


[ ![berak gravatar
image](//www.gravatar.com/avatar/67d5750ed525e660041a792f7ddce71f?s=32&d=identicon&r=PG)
](/users/2130/berak/)


  Further information  ï

  * Michael PÃ¶hnl et al.: [ âROS 2 Executor: How to make it efficient, real-time and deterministic?â ](https://www.apex.ai/roscon-21) . Workshop at ROS World 2021. Virtual event. 19 October 2021.

  * Ralph Lange: [ âAdvanced Execution Management with ROS 2â ](https://www.youtube.com/watch?v=Sz-nllmtcc8&t=109s) . ROS Industrial Conference. Virtual event. 16 December 2020.

  * Daniel Casini, Tobias Blass, Ingo LÃ¼tkebohle, and BjÃ¶rn Brandenburg: [ âResponse-Time Analysis of ROSÂ 2 Processing Chains under Reservation-Based Schedulingâ ](https://drops.dagstuhl.de/opus/volltexte/2019/10743/pdf/LIPIcs-ECRTS-2019-6.pdf) , Proc. of 31st ECRTS 2019, Stuttgart, Germany, July 2019.

[ Previous ](About-ROS-2-Parameters.html "About parameters in ROS 2") [ Next
](About-Topic-Statistics.html "About topic statistics")

* * *

© Copyright 2024, Open Robotics.

Built with [ Sphinx ](https://www.sphinx-doc.org/) using a [ theme
](https://github.com/readthedocs/sphinx_rtd_theme) provided by [ Read the Docs
](https://readthedocs.org) .

Other Versions  v: foxy

Releases

     [ Iron (latest) ](../../iron/index.html)
     [ Humble ](../../humble/index.html)
     [ Galactic (EOL) ](../../galactic/Concepts/About-Executors.html)
     [ Foxy (EOL) ](About-Executors.html)
     [ Eloquent (EOL) ](../../eloquent/index.html)
     [ Dashing (EOL) ](../../dashing/index.html)
     [ Crystal (EOL) ](../../crystal/index.html)

In Development

     [ Rolling ](../../rolling/index.html)


[ answered ** 2019-03-30 05:12:39 -0600  ** ](/answers/210948/revisions/)


It’s a shame we don’t have a nice way of solving this use case in a mature
server-side platform such as Node.js. In Java, for example, [ even some
numeric types are not atomic ](https://dzone.com/articles/longdouble-are-not-
atomic-in-java) — if you don’t synchronize their access, you could end up
having two threads change the value of a variable.


That said, I would have said this first if it had to precede what I'm telling you now. Having said that, what I'm telling you now is the same thing I just said about the annoying phrases "That said" and "Having said that".


[ __ ](/questions/) |


[ __ Wiki ](https://github.com/opencv/opencv/wiki)


where is the service.js file


So, at this point, many people might think our solution should be to add a new
module in the Node.js core and allow us to create and sync threads. But that
isn’t possible. If we add threads to JavaScript, then we are changing the
nature of the language.


  * Streamline the management of asynchronous I/O operations in user code
  * Particularly effective for applications with a high volume of concurrent I/O operations, such as managing file system operations, network requests, and database queries
  * Enables the efficient handling of I/O operations without causing blockages in the main event loop


Let’s see a simple example. First, we’ll implement the main file, create a
worker thread, and give it some data. The API is event-driven, but I’m going
to wrap it into a promise that resolves in the first message received from the
worker:


Not sure I understood, but is there any sync object acquired during the
manipulation of the shared data?


[ Get started for free  ](https://lp.logrocket.com/blg/signup)


    const { Worker, isMainThread, workerData, parentPort } = require('worker_threads')

    if (isMainThread) {
      function runService(workerData) {
        return new Promise((resolve, reject) => {
          const worker = new Worker(__filename, { workerData });
          worker.on('message', resolve);
          worker.on('error', reject);
          worker.on('exit', (code) => {
            if (code !== 0)
              reject(new Error(`Worker stopped with exit code ${code}`));
          })
        })
      }

      async function run() {
        const result = await runService('world')
        console.log(result);
      }

      run().catch(err => console.error(err))
    } else {
      // You can do any heavy stuff here, in a synchronous way
      // without blocking the "main thread"
      parentPort.postMessage({ hello: workerData })
    }


nice article concise and into the point, Thanks,


    class storedData {
      public:
        cv::Mat im, depth, outIm;
        void imCallback(const sensor_msgs::CompressedImageConstPtr& msgIm) {
          im = cv::imdecode(cv::Mat(msgIm->data),3);
        }

        void depthCallback(const sensor_msgs::CompressedImageConstPtr& msgDepth)
        {
          depth = cv::imdecode(cv::Mat(msgDepth->data),0);

          //    Performs something using both images(im & depth), Result : outIm    //

          cv::imshow("view", outIm);
          cv::waitKey(1);
        }
    };
    int main(int argc, char **argv)
    {
      ros::init(argc, argv, "PredictiveDisplay");
      ros::NodeHandle nh;
      storedData obj;
      cv::namedWindow("view", 0);
      cv::startWindowThread();

      ros::Subscriber subIm = nh.subscribe("/image", 2, &storedData::imCallback, &obj);
      ros::Subscriber subDepth = nh.subscribe("/depth", 2, &storedData::depthCallback, &obj);

      ros::AsyncSpinner spinner(2);
      spinner.start();
      ros::waitForShutdown();

      cv::destroyWindow("view");
    }


##  Over 200k developers use LogRocket to create better digital experiences