我在谷歌上搜索了很多共享(并发)数据结构,
所有这些似乎都是为线程共享的,而不是为进程共享的。
以共享哈希表为例,
如果要实现为多个进程共享,
所有 malloc
或对表的等效调用需要替换为 shmget
等
但是我没有看到这样的例子。
实现多个进程共享的数据结构是否可行?
我没有找到这样的例子是否意味着它不切实际?
最佳答案
主要问题是它不是独立于平台的方式。因此,假设您在某个 unix 系统上,为了在任意进程之间共享,我可能会在文件上使用 mmap
。这样做的好处是,您可以让任意多个进程共享它,这是识别共享点(文件)的简单方法,并且您还有一个免费的实际持久存储(使调试更容易)。不管你的数据结构有多复杂——它只是一 block 内存。因此,您唯一需要解决的问题是如何在您的进程之间同步写入访问 - 这实际上是特定于应用程序的(但是,如果您允许来自多个进程的写入,这并不容易)。
一些示例代码:
#include <sys/mman.h>
#include <fcntl.h>
...
struct my_structure *buf; /* just an example - can be arbitrary complex */
...
int fd = open("foo.bin", O_RDWR);
if (fd == -1) { /* if the file doesn't exist create your initial structure */
fd = open("foo.bin", O_RDWR | O_CREAT, 0700);
/* ... allocate enough space in the file or pre-fill with the structure ... */
/* (for safety you may do that in a separate process or using move-in atomically) */
}
buf = (struct my_structure*) mmap(0, sizeof(*buf), PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);
...
/* memory in buf is now shared across all processes ... */
/* if you want to synchronize that shared memory with the file use msync, but it's not needed for the sharing */
msync(buf, sizeof(*buf), MS_ASYNC);
/* when you're done, unmap */
munmap(buf, sizeof(*buf));
关于c - 实现多个进程共享的数据结构是否可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8737166/