Nodejs C ++ shared objects

Overview:

I have a NodeJS server with several C ++ modules doing one common "job". Some objects (C ++ objects, say "singletons") in these modules are shared and their states after initialization must be shared by each module. These objects must be initialized once during server startup.

Example:

A, B - separate C ++ modules that should be executed as one task

x, y, z - generic C ++ objects (maybe many of them)

  • The server receives the request (http) and processes it in A using x , y and z .
  • Reply (http) from A to client.
  • The server receives another (http) request and processes it in B using x , y and z as well .
  • Reply (http) from B to client.

Questions:

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

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

+3


source to share


1 answer


If you are using the boost library, you can create memory segments that can be shared between modules.

For example, you want to have 100 int

shared between modules A and B.

Then your module code will look like this (validation error 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 initialization code, then in your node.js code you need to require A first before you need B.



In your module B, you can access them like this (validation error 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 stores the kernel or filesystem and therefore you must explicitly free them when you are no longer using it. You can do it like this:

delete region;
remove("My100INTs");

      

Hope it helps.

+1


source







All Articles