Hope my question makes sense: Programming in C, can I create a hash table in a shared memory segment, so any process with proper permissions has access to the keys/values in it? If so, how can I specify at hash table creation that I want it put in the SHM? Is there any recommended hash table implementation that allows this? Thanks a lot
Off the top of my head I don't know any libraries that do this.
I do know that if you write your own or modify an existing library, the tricky thing that you need to do is track down and fix any code that uses pointers and replace it with code that uses base + offset.
The base would be the pointer returned by the shared memory create/open functions and it will be different in each process. The offset replaces what would be a pointer. When you need to locate a value via offset, you cast base to char*
, add the offset to that and then cast it to your_type*
. Something like (bucket_t*)((char*)base + offset)
.
That's assuming your hash implementation needs pointers at all. Some don't if they only use single-value buckets and no value lists.
The other tricky thing is that you need to manage the memory yourself. Instead of calling malloc(), you make your own function, maybe name it shm_hash_alloc(). A quick start is to just keep a pointer and increment it when allocating memory and don't bother with freeing it. Later you can use an array of pointers(offsets) to free lists of various power of two sizes or if you know your object types, a list for each type. In each free block you store the pointer to the next free block and you know the size because of what list it's on. There are even fancier methods but you probably don't need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With