概述:
我有一个 NodeJS 服务器,里面有几个 C++ 模块,执行一个整体“工作”。这些模块中的一些对象(C++ 对象,我们说“单例”)是通用的,它们在初始化后的状态应该在每个模块之间共享。这些对象的初始化必须在服务器启动期间完成一次。
示例:
A、B - 应该作为一个作业执行的独立 C++ 模块
x, y, z - 共享 C++ 对象(可能有很多)
- 服务器接收到一个 (http) 请求并在 A 中使用 x、y 和 z。
- (http) 响应从 A 发送到客户端。
- 服务器收到另一个 (http) 请求并在 B 中处理它,同样使用 x、y 和 z .
- (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/