Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c putting a hash table into a shared memory segment

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

like image 228
klayme Avatar asked Jan 20 '23 04:01

klayme


1 Answers

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.

like image 82
Zan Lynx Avatar answered Jan 30 '23 08:01

Zan Lynx