Implement a race-free allocation using POSIX
gnzlbg opened this issue · 2 comments
gnzlbg commented
See: https://groups.google.com/d/msg/comp.os.linux.development.system/Prx7ExCzsv4/saKCMIeJHhgJ
The algorithm should be:
void* alloc_mirrored(size_t size) {
assert(size % allocation_granularity() == 0);
// Create a file and unlink it:
int fd = shm_open("/unique_name", O_RDWR | O_CREAT | O_EXCL, 0600);
// handle_errors(fd);
shm_unlink("/unique_name");
// on Linux one might be able to avoid the link/unlink dance
// Resize the file
ftruncate(fd, size);
auto addr1 = mmap(0, 2*size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
// handle_errors(addr1);
auto addr2 = mmap(addr1+size, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
// handle_errors(addr2);
close(fd); // will stay alive until we unmap
return addr1;
}
void dealloc_mirrored(void* ptr, size_t size) {
munmap(ptr, 2 * size);
}
gnzlbg commented
Initial implementation in https://github.com/gnzlbg/slice_deque/tree/posix_race_free
gnzlbg commented
A race-free algorithm for Linux has been added, but a POSIX-compliant implementation using only /dev/shm
remains to be implemented.