SlideShare a Scribd company logo
/**
* @mainpage
* @anchor mainpage
* @brief
* @details
* @copyright Russell John Childs, PhD, 2017
* @author Russell John Childs, PhD
* @date 2017-02-26
*
* This file contains classes: SharedMemoryHashTable
*
* SharedMemoryHashTable implements a hash table using shared memory instead of
* heap memory. Two blocks of shared memory are created. The first is for the
* buckets. The second is "heap memory" for the linked list nodes that hold hash
* collisions. Each node contains a "next pointer" that holds the array index
* into the second block where the next node in the linked list resides. A C++
* placement new is used to initialise each node in shared memory. A simple
* memory management model is used for new/delete on Shared Memory involving a
* linked list of free memory slots that may be pushed and popped.
*
* Currently, only a subset of the interface for std::unordered_set/map is
* offered (insertions+deletions). In a future release, STL Allocators will be
* implemented that allow Shared Memory to be used for STL container classes.
*
* Compiled and tested under Linux Mint, using g++ 4.8.
*
* g++ options: -O0 -g3 -Wall -O0 -fopenmp -mavx -m64 -g -Wall -c
* -fmessage-length=0 -fno-omit-frame-pointer --fast-math
* -std=c++11 -I/opt/intel/vtune_amplifier_xe_2013/include/
*
* Linker options: -Wl,--no-as-needed -fopenmp
* -L/opt/intel/vtune_amplifier_xe_2013/lib64/
*
* Cmd line options: -lpthread -latomic -littnotify -ldl -lrt
*
* Documentation: Doxygen comments for interfaces, normal for impl.
*
* @file shared_memory_hash_table.cpp
* @see
* @ref mainpage
*/
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <iostream>
#include <string>
#include <functional>
/**
* addtogroup SharedMemoryContainers
* @{
*/
namespace SharedMemoryContainers
{
/**
* This class implements a hash table using shared memory instead of
* heap memory. Two blocks of shared memory are created. The first is for the
* buckets. The second is "heap memory" for the linked list nodes that hold hash
* collisions. Each node contains a "next pointer" that holds the array index
* into the second block where the next node in the linked list resides. A C++
* placement new is used to initialise each node in shared memory. A simple
* memory management model is used for new/delete on Shared Memory involving a
* linked list of free memory slots that may be pushed and popped.
*
* Currently, only a subset of the interface for std::unordered_set/map is
* offered (insertions+deletions). In a future release, STL Allocators will be
* implemented that allow Shared Memory to be used for STL container classes.
*
* Notes: The user type T must provide:
*
* (1) A default ctor
*
* (2) operator std::string(void) that returns a unique ID as an std::string of
* the form "/key" where key is some set of chars excluding '/'.
*
* @tparam T - The type of the item to be stored in hash map.
* @tparam Size - The number of buckets.
* @tparam NumItems - Number of items to be stored.
*
*/
template<typename T,unsigned Size,unsigned NumItems> class SharedMemoryHashTable
{
public:
/**
* Creates or accesses hash table in shared memory
*
* @param init {bool = false} - true iff hash table is being created, false
* if it already exists and is being accessed by a process.
*
* @param key {const std::string&="/shared_memory_hash_table"} - unique key
* for the shared memory of the form "/key" where key is some set of chars
* excluding '/'.
*
*/
SharedMemoryHashTable(
bool init = false, const std::string& key="/shared_memory_hash_table") :
m_key(key.c_str()),
m_buckets(0),
m_shared(0),
m_free(0)
{
//Shared memory for buckets
auto size = sizeof(unsigned)*Size;
auto shmid = shm_open(key.c_str(), O_CREAT | O_RDWR, 0666);
if(errno!=0) perror("shm_open: ");
ftruncate(shmid,size);
auto prot = PROT_READ | PROT_WRITE;
m_buckets=
static_cast<unsigned*>(mmap(0,size,prot,MAP_SHARED,shmid,0));
if(init) for(unsigned i=0; i<Size; ++i) m_buckets[i]=0;
close(shmid);
//Shared memory for linked list nodes
size = sizeof(LinkedList)*(NumItems+1);
shmid = shm_open((key+"nodes").c_str(), O_CREAT | O_RDWR, 0666);
if(errno!=0) perror("shm_open: ");
ftruncate(shmid,size);
m_shared=static_cast<LinkedList*>(mmap(0,size,prot,MAP_SHARED,shmid,0));
//Stored "ptr" to free memory in m_shared[0] so all processes see it
m_free = &m_shared->m_next;
close(shmid);
//Create "heap" of free memory (linked list of free slots)
if(init)
{
for(unsigned i=1; i <= NumItems; ++i)
{
(m_shared+*m_free)->m_next = i;
*m_free = i;
}
m_free = &(m_shared->m_next=1);
}
}
/**
* Detach shared memory associated with this hash table
*/
~SharedMemoryHashTable(void)
{
munmap(m_shared, NumItems*sizeof(LinkedList));
munmap(m_buckets, sizeof(unsigned)*Size);
shm_unlink(m_key.c_str());
shm_unlink((m_key+"nodes").c_str());
}
/**
* This class provides the linked list for hash collisions.
*
*/
struct LinkedList
{
T m_data;
unsigned m_next;
/**
* @param data {const T&} - item to be placed in linked list node
*/
LinkedList(const T& data = T()) :
m_data(data),
m_next(0)
{
}
/**
* Dtor
*/
~LinkedList(void)
{
}
};
/**
* @param key {const std::string&} - unique item id to be searched for
*
* @return T* - reference to item with specified id or NULL if not found
*
*/
T* find(const std::string& key)
{
T* ret_val = 0;
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
//Search for key
auto next = m_buckets[index];
while( next != 0 && ret_val==0)
{
//If key found ...
if(std::string((m_shared+next)->m_data)==key)
{
//Return value = found item
ret_val = &(m_shared+next)->m_data;
}
//Keep traversing linked list
next=(m_shared+next)->m_next;
}
return ret_val;
}
/**
* @param key {const std::string&} - unique item id
*
* @param in {const T&} - item to be inserted
*
* @return std::pair<T*, bool> - {existing_item_address, false} iff item
* already exists, {inserted_item_address, true} if item does not exist
*
*/
std::pair<T*, bool> insert(const std::string& key, const T& in)
{
//Get item if it exists, or NULL
T* ret_val = find(key);
bool is_success = false;
//If item does not exist, create it on the Shared Memory "heap"
if(ret_val==0)
{
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
//Create new linked list node and return reference to stored item
unsigned free_slot = *m_free;
*m_free = (m_shared+*m_free)->m_next;
LinkedList* linked_list =new(m_shared+free_slot) LinkedList(in);
linked_list->m_next=m_buckets[index];
m_buckets[index]=free_slot;
//new item and success
ret_val = &linked_list->m_data;
is_success = true;
}
return std::make_pair(ret_val, is_success);
}
/**
* @param key {const std::string&} - unique item id
*
* @return T& - reference to item with specified id
*
*/
T& operator[](const std::string& key)
{
return *insert(key, T()).first;
}
/**
* @param key {const std::string&} - unique item id
*
* @param in {const T&} - item to be inserted
*
* @return std::pair<T*, bool> - {existing_item_address, false} iff item
* already exists, {inserted_item_address, true} if item does not exist
*
*/
void erase(const std::string& key)
{
//Convert key to bucket array index
auto index = std::hash<std::string>{}(key)%Size;
//Search for key
auto prev = m_buckets[index];
auto next = prev;
while( next != 0 )
{
//If key found ...
if(std::string((m_shared+next)->m_data)==key)
{
//delete found item
if(prev==m_buckets[index]) m_buckets[index] =
((m_shared+prev)->m_next=(m_shared+next)->m_next);
(m_shared+next)->m_next = *m_free;
*m_free = next;
}
//Keep traversing linked list
prev = next;
next=(m_shared+next)->m_next;
}
}
private:
std::string m_key;
unsigned* m_buckets;
LinkedList* m_shared;
unsigned* m_free;
};
}
/**
* @}
*/
int main(void)
{
using namespace SharedMemoryContainers;
//Raw Data
struct RawData
{
unsigned m_user_id;
unsigned m_dest_id;
std::string m_branch;
operator std::string(void)
{
return std::string(m_branch);
}
};
//Create a 100-bucket hash table
const int buckets = 100;
const int items = 5;
typedef SharedMemoryHashTable<RawData, buckets, items> Table;
Table shared_memory_hash_table(true);
//Parent process
unsigned user_id = 0;
unsigned dest_id = 1000;
//Insert values into shared memory hash table
std::cout << "=====================================" << std::endl;
std::cout << "Inserting values via parent process" << std::endl;
//Loop over keys
for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})
{
//Insert item into hash table
RawData raw_data = RawData{user_id++, dest_id--, str};
//str.copy(raw_data.m_branch, str.size());
if(str == "a")
{
shared_memory_hash_table.insert(raw_data.m_branch, raw_data);
}
else
{
shared_memory_hash_table[raw_data.m_branch]=raw_data;
}
std::cout << "hash_table[" << raw_data.m_branch << "]={"
<< raw_data.m_user_id << ", "
<< raw_data.m_dest_id << ", "
<< raw_data.m_branch << "}"
<< std::endl;
//Validate insertion
std::cout << "Verify: hash_table[" << raw_data.m_branch << "] == {"
<< shared_memory_hash_table[raw_data.m_branch].m_user_id << ", "
<< shared_memory_hash_table[raw_data.m_branch].m_dest_id << ", "
<< shared_memory_hash_table[raw_data.m_branch].m_branch << "}"
<< std::endl;
}
//Fork child process
pid_t p_id = fork();
if (p_id == 0)
{
Table shared_memory_hash_table;
//Extract values from shared memory hash table
std::cout << "=====================================" << std::endl;
std::cout << "Extracting values via child process" << std::endl;
//Loop over keys
for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})
{
//Find item for given key
auto& item = shared_memory_hash_table[str.c_str()];
std::cout << "hash_table[" << str << "] == {"
<< item.m_user_id << ", "
<< item.m_dest_id << ", "
<< item.m_branch << "}"
<< std::endl;
}
std::cout << "=====================================" << std::endl;
std::cout << "deleting key="bb" via child process" << std::endl;
shared_memory_hash_table.erase("bb");
std::cout << "Extracting values left via child process" << std::endl;
for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})
{
//Find item for given key
auto item = shared_memory_hash_table.find(str.c_str());
if(item !=0)
{
std::cout << "hash_table[" << str << "] == {"
<< item->m_user_id << ", "
<< item->m_dest_id << ", "
<< item->m_branch << "}"
<< std::endl;
}
else
{
std::cout << str << " not found in hash table." << std::endl;
}
}
std::cout << "=====================================" << std::endl;
}
else
{
int status;
waitpid(p_id, &status, 0);
std::cout << "=====================================" << std::endl;
std::cout << "Extracting values left via parent process" << std::endl;
for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})
{
//Find item for given key
auto item = shared_memory_hash_table.find(str.c_str());
if(item !=0)
{
std::cout << "hash_table[" << str << "] == {"
<< item->m_user_id << ", "
<< item->m_dest_id << ", "
<< item->m_branch << "}"
<< std::endl;
}
else
{
std::cout << str << " not found in hash table." << std::endl;
}
}
}
return 0;
}

More Related Content

Viewers also liked

Brain mri reports
Brain mri reportsBrain mri reports
Brain mri reports
Venkata Tejaswi
 
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
Proactive Advisor Magazine
 
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
Proactive Advisor Magazine
 
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
Proactive Advisor Magazine
 
9 orange square 8 love
9 orange square 8 love9 orange square 8 love
9 orange square 8 love
Migdal Eden
 
B2 5 Monitors
B2 5 MonitorsB2 5 Monitors
B2 5 Monitors
papettas
 
Entradablog
EntradablogEntradablog
Entradablog
belenlavadoandrade
 
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
Proactive Advisor Magazine
 
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
Proactive Advisor Magazine
 
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
Proactive Advisor Magazine
 
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
Proactive Advisor Magazine
 
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
Proactive Advisor Magazine
 
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
Proactive Advisor Magazine
 
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
Proactive Advisor Magazine
 
Toronto’s attractions!
Toronto’s attractions!Toronto’s attractions!
Toronto’s attractions!
Ishie TheFatFishy
 
Tugas PPKN
Tugas PPKNTugas PPKN
Tugas PPKN
gagallogin
 
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
Proactive Advisor Magazine
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Russell Childs
 

Viewers also liked (18)

Brain mri reports
Brain mri reportsBrain mri reports
Brain mri reports
 
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
Randy Kerns, CIC, ChFC – Proactive Advisor Magazine – Volume 5 Issue 1
 
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
Jerry Ganz, CFP – Proactive Advisor Magazine – Volume 5 Issue 3
 
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
Jeff Pesta, LUTCF – Proactive Advisor Magazine – Volume 5 Issue 11
 
9 orange square 8 love
9 orange square 8 love9 orange square 8 love
9 orange square 8 love
 
B2 5 Monitors
B2 5 MonitorsB2 5 Monitors
B2 5 Monitors
 
Entradablog
EntradablogEntradablog
Entradablog
 
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
Johnathon Davis – Proactive Advisor Magazine – Volume 6, Issue 2
 
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
Chris Gurnee – Proactive Advisor Magazine – Volume 6, Issue 3
 
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
Bob Pearson – Proactive Advisor Magazine – Volume 6, Issue 11
 
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
Ryan Finnell – Proactive Advisor Magazine – Volume 6, Issue 9
 
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
Don Meredith, CRPC – Proactive Advisor Magazine – Volume 6, Issue 5
 
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
Phylyp Wagner, CFP & Matt Quattlebaum, CFP – Proactive Advisor Magazine – Vol...
 
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
Trish Beine – Proactive Advisor Magazine – Volume 5 Issue 2
 
Toronto’s attractions!
Toronto’s attractions!Toronto’s attractions!
Toronto’s attractions!
 
Tugas PPKN
Tugas PPKNTugas PPKN
Tugas PPKN
 
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
Brian Glaze & Larry Ware, CRPC, CLTC – Proactive Advisor Magazine – Volume 5 ...
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
 

Similar to Shared_memory_hash_table

Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdf
arihantstoneart
 
This project will implement a simple usernamepassword lookup system.pdf
This project will implement a simple usernamepassword lookup system.pdfThis project will implement a simple usernamepassword lookup system.pdf
This project will implement a simple usernamepassword lookup system.pdf
ezhilvizhiyan
 
Program 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdfProgram 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdf
ezzi552
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux Kernel
Divye Kapoor
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdf
deepaksatrker
 
Complete code in Java The hashtable you'll be making will use String.pdf
Complete code in Java   The hashtable you'll be making will use String.pdfComplete code in Java   The hashtable you'll be making will use String.pdf
Complete code in Java The hashtable you'll be making will use String.pdf
aarifi9988
 
Hash table (2)
Hash table (2)Hash table (2)
Hash table (2)
aliraza202366
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
ssuser688516
 
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
ajoy21
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdf
flashfashioncasualwe
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
amirthagiftsmadurai
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
vicky309441
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
formicreation
 
You are to write an efficient program that will read a dictionary of.pdf
You are to write an efficient program that will read a dictionary of.pdfYou are to write an efficient program that will read a dictionary of.pdf
You are to write an efficient program that will read a dictionary of.pdf
fortmdu
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
mohammadirfan136964
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
alokindustries1
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
sibokac
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 

Similar to Shared_memory_hash_table (20)

Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdf
 
This project will implement a simple usernamepassword lookup system.pdf
This project will implement a simple usernamepassword lookup system.pdfThis project will implement a simple usernamepassword lookup system.pdf
This project will implement a simple usernamepassword lookup system.pdf
 
Program 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdfProgram 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdf
 
The TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux KernelThe TCP/IP Stack in the Linux Kernel
The TCP/IP Stack in the Linux Kernel
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdf
 
Complete code in Java The hashtable you'll be making will use String.pdf
Complete code in Java   The hashtable you'll be making will use String.pdfComplete code in Java   The hashtable you'll be making will use String.pdf
Complete code in Java The hashtable you'll be making will use String.pdf
 
Hash table (2)
Hash table (2)Hash table (2)
Hash table (2)
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
(C++ exercise) 3. Implement a circular, doubly linked list with a ha.docx
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdf
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
 
You are to write an efficient program that will read a dictionary of.pdf
You are to write an efficient program that will read a dictionary of.pdfYou are to write an efficient program that will read a dictionary of.pdf
You are to write an efficient program that will read a dictionary of.pdf
 
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfPart 1)#include stdio.h #include stdlib.h #include pthrea.pdf
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf
 
Lab8
Lab8Lab8
Lab8
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
 
ch 7 POSIX.pptx
ch 7 POSIX.pptxch 7 POSIX.pptx
ch 7 POSIX.pptx
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 

More from Russell Childs

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdf
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching
String searchingString searching
String searching
Russell Childs
 
Permute
PermutePermute
Permute
PermutePermute
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
Russell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
Russell Childs
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pages
Russell Childs
 
Relativity 2
Relativity 2Relativity 2
Relativity 2
Russell Childs
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016
Russell Childs
 
Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UML
Russell Childs
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcasting
Russell Childs
 
Interview uml design
Interview uml designInterview uml design
Interview uml design
Russell Childs
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_Childs
Russell Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
Russell Childs
 
K d tree_cpp
K d tree_cppK d tree_cpp
K d tree_cpp
Russell Childs
 
Multithreaded sockets c++11
Multithreaded sockets c++11Multithreaded sockets c++11
Multithreaded sockets c++11
Russell Childs
 
IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.
Russell Childs
 

More from Russell Childs (20)

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdf
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching
String searchingString searching
String searching
 
Permute
PermutePermute
Permute
 
Permute
PermutePermute
Permute
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pages
 
Relativity 2
Relativity 2Relativity 2
Relativity 2
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016
 
Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UML
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcasting
 
Interview uml design
Interview uml designInterview uml design
Interview uml design
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
 
K d tree_cpp
K d tree_cppK d tree_cpp
K d tree_cpp
 
Multithreaded sockets c++11
Multithreaded sockets c++11Multithreaded sockets c++11
Multithreaded sockets c++11
 
IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.IBM Kinexa Prove It! C++ programming test results.
IBM Kinexa Prove It! C++ programming test results.
 

Recently uploaded

Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 

Recently uploaded (20)

Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 

Shared_memory_hash_table

  • 1. /** * @mainpage * @anchor mainpage * @brief * @details * @copyright Russell John Childs, PhD, 2017 * @author Russell John Childs, PhD * @date 2017-02-26 * * This file contains classes: SharedMemoryHashTable * * SharedMemoryHashTable implements a hash table using shared memory instead of * heap memory. Two blocks of shared memory are created. The first is for the * buckets. The second is "heap memory" for the linked list nodes that hold hash * collisions. Each node contains a "next pointer" that holds the array index * into the second block where the next node in the linked list resides. A C++ * placement new is used to initialise each node in shared memory. A simple * memory management model is used for new/delete on Shared Memory involving a * linked list of free memory slots that may be pushed and popped. * * Currently, only a subset of the interface for std::unordered_set/map is * offered (insertions+deletions). In a future release, STL Allocators will be * implemented that allow Shared Memory to be used for STL container classes. * * Compiled and tested under Linux Mint, using g++ 4.8. * * g++ options: -O0 -g3 -Wall -O0 -fopenmp -mavx -m64 -g -Wall -c * -fmessage-length=0 -fno-omit-frame-pointer --fast-math * -std=c++11 -I/opt/intel/vtune_amplifier_xe_2013/include/ * * Linker options: -Wl,--no-as-needed -fopenmp * -L/opt/intel/vtune_amplifier_xe_2013/lib64/ * * Cmd line options: -lpthread -latomic -littnotify -ldl -lrt * * Documentation: Doxygen comments for interfaces, normal for impl. * * @file shared_memory_hash_table.cpp * @see * @ref mainpage */ #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <iostream> #include <string> #include <functional> /** * addtogroup SharedMemoryContainers * @{ */ namespace SharedMemoryContainers { /** * This class implements a hash table using shared memory instead of * heap memory. Two blocks of shared memory are created. The first is for the * buckets. The second is "heap memory" for the linked list nodes that hold hash * collisions. Each node contains a "next pointer" that holds the array index * into the second block where the next node in the linked list resides. A C++ * placement new is used to initialise each node in shared memory. A simple
  • 2. * memory management model is used for new/delete on Shared Memory involving a * linked list of free memory slots that may be pushed and popped. * * Currently, only a subset of the interface for std::unordered_set/map is * offered (insertions+deletions). In a future release, STL Allocators will be * implemented that allow Shared Memory to be used for STL container classes. * * Notes: The user type T must provide: * * (1) A default ctor * * (2) operator std::string(void) that returns a unique ID as an std::string of * the form "/key" where key is some set of chars excluding '/'. * * @tparam T - The type of the item to be stored in hash map. * @tparam Size - The number of buckets. * @tparam NumItems - Number of items to be stored. * */ template<typename T,unsigned Size,unsigned NumItems> class SharedMemoryHashTable { public: /** * Creates or accesses hash table in shared memory * * @param init {bool = false} - true iff hash table is being created, false * if it already exists and is being accessed by a process. * * @param key {const std::string&="/shared_memory_hash_table"} - unique key * for the shared memory of the form "/key" where key is some set of chars * excluding '/'. * */ SharedMemoryHashTable( bool init = false, const std::string& key="/shared_memory_hash_table") : m_key(key.c_str()), m_buckets(0), m_shared(0), m_free(0) { //Shared memory for buckets auto size = sizeof(unsigned)*Size; auto shmid = shm_open(key.c_str(), O_CREAT | O_RDWR, 0666); if(errno!=0) perror("shm_open: "); ftruncate(shmid,size); auto prot = PROT_READ | PROT_WRITE; m_buckets= static_cast<unsigned*>(mmap(0,size,prot,MAP_SHARED,shmid,0)); if(init) for(unsigned i=0; i<Size; ++i) m_buckets[i]=0; close(shmid); //Shared memory for linked list nodes size = sizeof(LinkedList)*(NumItems+1); shmid = shm_open((key+"nodes").c_str(), O_CREAT | O_RDWR, 0666); if(errno!=0) perror("shm_open: "); ftruncate(shmid,size); m_shared=static_cast<LinkedList*>(mmap(0,size,prot,MAP_SHARED,shmid,0)); //Stored "ptr" to free memory in m_shared[0] so all processes see it m_free = &m_shared->m_next; close(shmid); //Create "heap" of free memory (linked list of free slots) if(init) { for(unsigned i=1; i <= NumItems; ++i) {
  • 3. (m_shared+*m_free)->m_next = i; *m_free = i; } m_free = &(m_shared->m_next=1); } } /** * Detach shared memory associated with this hash table */ ~SharedMemoryHashTable(void) { munmap(m_shared, NumItems*sizeof(LinkedList)); munmap(m_buckets, sizeof(unsigned)*Size); shm_unlink(m_key.c_str()); shm_unlink((m_key+"nodes").c_str()); } /** * This class provides the linked list for hash collisions. * */ struct LinkedList { T m_data; unsigned m_next; /** * @param data {const T&} - item to be placed in linked list node */ LinkedList(const T& data = T()) : m_data(data), m_next(0) { } /** * Dtor */ ~LinkedList(void) { } }; /** * @param key {const std::string&} - unique item id to be searched for * * @return T* - reference to item with specified id or NULL if not found * */ T* find(const std::string& key) { T* ret_val = 0; //Convert key to bucket array index auto index = std::hash<std::string>{}(key)%Size; //Search for key auto next = m_buckets[index]; while( next != 0 && ret_val==0) { //If key found ... if(std::string((m_shared+next)->m_data)==key) { //Return value = found item
  • 4. ret_val = &(m_shared+next)->m_data; } //Keep traversing linked list next=(m_shared+next)->m_next; } return ret_val; } /** * @param key {const std::string&} - unique item id * * @param in {const T&} - item to be inserted * * @return std::pair<T*, bool> - {existing_item_address, false} iff item * already exists, {inserted_item_address, true} if item does not exist * */ std::pair<T*, bool> insert(const std::string& key, const T& in) { //Get item if it exists, or NULL T* ret_val = find(key); bool is_success = false; //If item does not exist, create it on the Shared Memory "heap" if(ret_val==0) { //Convert key to bucket array index auto index = std::hash<std::string>{}(key)%Size; //Create new linked list node and return reference to stored item unsigned free_slot = *m_free; *m_free = (m_shared+*m_free)->m_next; LinkedList* linked_list =new(m_shared+free_slot) LinkedList(in); linked_list->m_next=m_buckets[index]; m_buckets[index]=free_slot; //new item and success ret_val = &linked_list->m_data; is_success = true; } return std::make_pair(ret_val, is_success); } /** * @param key {const std::string&} - unique item id * * @return T& - reference to item with specified id * */ T& operator[](const std::string& key) { return *insert(key, T()).first; } /** * @param key {const std::string&} - unique item id * * @param in {const T&} - item to be inserted * * @return std::pair<T*, bool> - {existing_item_address, false} iff item * already exists, {inserted_item_address, true} if item does not exist * */ void erase(const std::string& key) { //Convert key to bucket array index auto index = std::hash<std::string>{}(key)%Size;
  • 5. //Search for key auto prev = m_buckets[index]; auto next = prev; while( next != 0 ) { //If key found ... if(std::string((m_shared+next)->m_data)==key) { //delete found item if(prev==m_buckets[index]) m_buckets[index] = ((m_shared+prev)->m_next=(m_shared+next)->m_next); (m_shared+next)->m_next = *m_free; *m_free = next; } //Keep traversing linked list prev = next; next=(m_shared+next)->m_next; } } private: std::string m_key; unsigned* m_buckets; LinkedList* m_shared; unsigned* m_free; }; } /** * @} */ int main(void) { using namespace SharedMemoryContainers; //Raw Data struct RawData { unsigned m_user_id; unsigned m_dest_id; std::string m_branch; operator std::string(void) { return std::string(m_branch); } }; //Create a 100-bucket hash table const int buckets = 100; const int items = 5; typedef SharedMemoryHashTable<RawData, buckets, items> Table; Table shared_memory_hash_table(true); //Parent process unsigned user_id = 0; unsigned dest_id = 1000; //Insert values into shared memory hash table std::cout << "=====================================" << std::endl; std::cout << "Inserting values via parent process" << std::endl; //Loop over keys for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"})
  • 6. { //Insert item into hash table RawData raw_data = RawData{user_id++, dest_id--, str}; //str.copy(raw_data.m_branch, str.size()); if(str == "a") { shared_memory_hash_table.insert(raw_data.m_branch, raw_data); } else { shared_memory_hash_table[raw_data.m_branch]=raw_data; } std::cout << "hash_table[" << raw_data.m_branch << "]={" << raw_data.m_user_id << ", " << raw_data.m_dest_id << ", " << raw_data.m_branch << "}" << std::endl; //Validate insertion std::cout << "Verify: hash_table[" << raw_data.m_branch << "] == {" << shared_memory_hash_table[raw_data.m_branch].m_user_id << ", " << shared_memory_hash_table[raw_data.m_branch].m_dest_id << ", " << shared_memory_hash_table[raw_data.m_branch].m_branch << "}" << std::endl; } //Fork child process pid_t p_id = fork(); if (p_id == 0) { Table shared_memory_hash_table; //Extract values from shared memory hash table std::cout << "=====================================" << std::endl; std::cout << "Extracting values via child process" << std::endl; //Loop over keys for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"}) { //Find item for given key auto& item = shared_memory_hash_table[str.c_str()]; std::cout << "hash_table[" << str << "] == {" << item.m_user_id << ", " << item.m_dest_id << ", " << item.m_branch << "}" << std::endl; } std::cout << "=====================================" << std::endl; std::cout << "deleting key="bb" via child process" << std::endl; shared_memory_hash_table.erase("bb"); std::cout << "Extracting values left via child process" << std::endl; for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"}) { //Find item for given key auto item = shared_memory_hash_table.find(str.c_str()); if(item !=0) { std::cout << "hash_table[" << str << "] == {" << item->m_user_id << ", " << item->m_dest_id << ", " << item->m_branch << "}" << std::endl; } else { std::cout << str << " not found in hash table." << std::endl; }
  • 7. } std::cout << "=====================================" << std::endl; } else { int status; waitpid(p_id, &status, 0); std::cout << "=====================================" << std::endl; std::cout << "Extracting values left via parent process" << std::endl; for(std::string str : {"a", "bb", "ccc", "dddd", "eeeee"}) { //Find item for given key auto item = shared_memory_hash_table.find(str.c_str()); if(item !=0) { std::cout << "hash_table[" << str << "] == {" << item->m_user_id << ", " << item->m_dest_id << ", " << item->m_branch << "}" << std::endl; } else { std::cout << str << " not found in hash table." << std::endl; } } } return 0; }