如何在 id 序列中有效地重用已发布的 id

问题描述

假设我们有一个 PID 生成器,它为 7 个进程 {1,2,3,4,5,6,7} 生成了 7 个 ID。 进程 3 和 6 已经完成,id 3 和 6 可供抢夺。现在我们开始三个新进程。 如何实现高效的算法,首先按此顺序为它们分配 id 3、6 和 8。

我正在考虑将已发布的 Id 存储在排序树中,但这需要额外的结构来跟踪序列中的“漏洞”。使用中 id 的排序树结构有助于获得下一个最大的 id,但它是否在寻找漏洞方面占上风?

解决方法

只需使用一个优先级队列(堆)来追踪所有的空洞,就像这样:

#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;
}