c++ - nodejs C++ 共享对象

标签 c++ node.js

概述:

我有一个 NodeJS 服务器,里面有几个 C++ 模块,执行一个整体“工作”。这些模块中的一些对象(C++ 对象,我们说“单例”)是通用的,它们在初始化后的状态应该在每个模块之间共享。这些对象的初始化必须在服务器启动期间完成一次。

示例:

A、B - 应该作为一个作业执行的独立 C++ 模块

x, y, z - 共享 C++ 对象(可能有很多)

  1. 服务器接收到一个 (http) 请求并在 A 中使用 xyz
  2. (http) 响应从 A 发送到客户端。
  3. 服务器收到另一个 (http) 请求并在 B 中处理它,同样使用 xyz .
  4. (http) 响应从 B 发送到客户端。

问题:

您能告诉我是否有一些已知的在所有 C++ 模块之间初始化和共享这些对象的最佳实践吗?

NodeJS 中特定 C++ 模块的生命周期是什么?它们什么时候从内存中删除?

最佳答案

如果您使用的是 boost 库,则可以创建可在模块之间共享的内存段。

例如,您希望在模块 A 和 B 之间共享 100 个 int

那么您的模块 A 的代码将如下所示(为简洁起见省略了错误检查):

// 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;
}

由于 A 包含初始化代码,因此在您的 node.js 代码中,您必须先 require A,然后再 require B。

在您的模块 B 中,您可以像这样访问它们(为简洁起见省略了错误检查):

// 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;
}

此共享内存具有内核或文件系统持久性,因此,当您不再使用它时,您必须显式地释放它们。你可以这样做:

delete region;
remove("My100INTs");

希望这对您有所帮助。

关于c++ - nodejs C++ 共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140340/

相关文章:

javascript - 有什么方法可以使 javascript 中的嵌套回调代码更具可读性吗?

C++ & WinApi - 在创建的窗口中从键盘到屏幕的文本输出

javascript - Node.js async.each - "callback was already called"

Javascript 文件或模块范围内的变量

c++ - 将视锥从相机空间转换为光空间以进行阴影贴图时遇到重大问题

javascript - 当我添加新的中间件来处理express.js中的路径时,404未找到

javascript - node.js csv如何处理不良数据

c++ - 微软/CppRestSDK 卡萨布兰卡,Visual Studio 2017

c++ - 如何使用抽象类的 Polymorphy 2D-Array 创建?

c++ - 用于删除 C++ 中的注释的程序不起作用