Creating a "interrupt safe" memory pool

227 Views Asked by At

I have written a simple memory pool which is thread-safe on multi-threaded systems (i.e. systems with an OS which handles thread scheduling). It uses some simple locking around each function, but it relies on the fact that another thread won't hold the lock forever. It uses a linked list of blocks, i.e. the head of the list always points to the next free block (and allocated blocks are not in the list).

But to make this work with interrupts, where I cannot risk locking inside the interrupt, the only thing I could think of was:

while (true)
{
    // iterate through the list of blocks and atomically acquire
    // a previously unacquired block

    for (int i = 0; i < pool->numberOfBlocks; i++)
    {
        // try to acquire this block atomically
        if (atomic_exchange(&pool->isBlockAcquired[i], 1) == 0)
             return pool->blocks[i];
    }
}

But this is far less performant than a linked list with locking, since it needs to iterate through the entire array. On the other hand, I don't want to have "one memory pool per interrupt" because I'd like to be able to allocate in one interrupt and free in a different one (if needed).

So I guess my question boils down to: how do I create a interrupt-safe linked list which I can use for a memory pool? Or (if I made an "XY problem") how do I create a simple lockless interrupt-safe memory pool, which can be shared among interrupts?

0

There are 0 best solutions below