Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs C++ shared objects

Tags:

c++

node.js

Overview:

I have a NodeJS server with a few C++ modules in it, executing one overall "job". Some objects (C++ objects, let's say "singletons") in these modules are common and their states after initialization should be shared between each module. The initialization of those objects has to be done once during server startup.

Example:

A, B - separate C++ modules which should be executed as one job

x, y, z - shared C++ objects (possibly a lot of them)

  1. Server receives a (http) request and processes it in A using x, y and z.
  2. The (http) response goes from A to the client.
  3. Server receives another (http) request and processes it in B also using x, y and z.
  4. The (http) response goes from B to the client.

Questions:

Can you tell me if there is some known best practice of initialization and sharing of these objects between all C++ modules?

What is the lifecycle of a particular C++ module in NodeJS? When are they removed from the memory?

like image 208
korniak Avatar asked Mar 25 '26 13:03

korniak


1 Answers

If you're using boost library, you could create memory segments that can be shared among modules.

For example, you want to have 100 int shared between module A and B.

Then your module A's code is gonna look like this (error checking omitted for brevity):

// Shared memory creation
shared_memory_object shm (create_only, "My100INTs", read_write);
shm.truncate(100 * sizeof(int));
mapped_region region(shm, read_write);

// Get the address of the first element
int* theMemory = static_cast<int*>(region.get_address());

// Initialization Code
for (int i = 0; i < 100; i++) {
    *(theMemory + i) = i;
}

Since A contains the initialization code, then in your node.js code you must first require A before you require B.

In your module B, you can access them like this (error checking omitted for brevity):

// Open the previously created shared memory
shared_memory_object shm (open_only, "My100INTs", read_write);
mapped_region region(shm, read_write);

// Get the address of the first element
int* theMemory = static_cast<int*>(region.get_address());

// Do modification
for (int i = 0; i < 100; i++) {
    *(theMemory + i) *= 2;
}

This shared memory has kernel or filesystem persistence and therefore, you must explicitly deallocate them when you no longer using it. You can do it like this:

delete region;
remove("My100INTs");

Hope this helps.

like image 123
CodeBeginner Avatar answered Mar 27 '26 02:03

CodeBeginner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!