Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently reuse released ids in id sequence

Lets say we have PID generator that generated 7 ids for 7 processes {1,2,3,4,5,6,7}. Process 3 and 6 have finished and id 3 and 6 are up for grabs. Now we start three new processes. How to implement efficient algorithm that will first assign them ids 3, 6, and 8 in this very sequence.

I was thinking about storing released Ids in a sorted tree, but that takes extra structure to track the 'holes' in the sequence. Having sorted tree structure of ids in use helps to get next biggest id, but does it give any upper hand in finding the holes?

like image 375
user1079475 Avatar asked Oct 19 '25 13:10

user1079475


1 Answers

Just use a priority queue(heap) to trace all the hole, like this:

#include <queue>

std::priority_queue<int> q;
int all_free_after = 1;

void free_one_pid(int pid) {
    // the priority_queue returns the largest one inside the queue
    // but we want the smallest one
    // so we are push the opposite number into the queue
    q.push(-pid);
}

int get_one_pid() {
    if (q.empty()) { return all_free_after++; }
    int res = -q.top();
    q.pop();
    return res;
}
like image 198
szdytom Avatar answered Oct 22 '25 03:10

szdytom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!