gnzlbg / slice_deque

A contiguous-in-memory double-ended queue that derefs into a slice
https://docs.rs/crate/slice-deque/
Other
154 stars 21 forks source link

Implement a race-free allocation using POSIX #10

Open gnzlbg opened 6 years ago

gnzlbg commented 6 years ago

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 6 years ago

Initial implementation in https://github.com/gnzlbg/slice_deque/tree/posix_race_free

gnzlbg commented 6 years ago

A race-free algorithm for Linux has been added, but a POSIX-compliant implementation using only /dev/shm remains to be implemented.