Skip to content

Timeline points and command-list reuse

A timeline point answers one question: has the GPU finished this piece of work yet? This page explains why you need to ask, what a point is, and the one rule that follows from it.

The problem: the CPU runs ahead of the GPU

submit does not run your commands. It hands them to the GPU and returns at once, usually before the GPU has even started. Your program goes on while the GPU works in the background, often one or two frames behind.

That is good for speed, and it creates a hazard. Right after submit:

  • the result buffer does not hold the result yet;
  • the buffers, textures and pipelines the commands use are still being used;
  • the command list itself is still being read by the GPU.

If you read the result, destroy a buffer, or re-record the list now, you race the GPU: you get stale data, a crash, or a lost device, and often only on some GPUs. You need a way to know when the GPU is done. That is what a timeline point is for.

What a timeline point is

Think of a ticket counter at a bakery:

  • each customer takes a ticket with a number: 1, 2, 3, ...;
  • a display shows "now served: n", and n only goes up;
  • your order is ready once the display shows your number or more.

In RI:

Bakery RI
The display The queue's timeline: a 64-bit counter kept by the GPU.
Taking a ticket submit(queue, cmd), which returns an RI::TimelinePoint.
Your ticket's number point.value.
"Is my order ready?" isReached(queue, point): is the counter >= point.value?
Waiting at the counter wait(queue, point): sleep until it is.

A TimelinePoint is just that number, wrapped in a struct:

struct TimelinePoint {
    uint64 value = 0;
};

It is a plain value: you can copy it, store it, and compare its value field.

A timeline, step by step

Three submissions on the graphics queue:

sequenceDiagram
    participant CPU
    participant Queue as Graphics queue
    participant Counter as Queue counter
    Note over Counter: 0
    CPU->>Queue: submit(A) returns {1}
    CPU->>Queue: submit(B) returns {2}
    CPU->>Queue: submit(C) returns {3}
    Note over CPU: goes on with other work
    Queue->>Queue: runs A
    Queue->>Counter: A done: 1
    Queue->>Queue: runs B
    Queue->>Counter: B done: 2
    Queue->>Queue: runs C
    Queue->>Counter: C done: 3

At any moment you can ask about any of the three points:

  • just after the three submits, the counter is probably still 0: none is reached;
  • when it shows 2, points {1} and {2} are reached, {3} is not;
  • once it shows 3, all three are.

Two facts make points easy to use:

  1. Reaching a point means every earlier point is reached too. The queue runs its submissions in order, so if you hold several points, you only need to wait for the latest.
  2. The point {0} is always reached. A default-constructed TimelinePoint means "no GPU work to wait for", which is handy as "never used yet".

Asking: wait and isReached

RI::Queue &queue = device.graphicsQueue;
const RI::TimelinePoint done = RI::submit(queue, cmd);
RI::wait(queue, done); // blocks until the GPU has finished this submission
  • RI::wait(queue, point) blocks the CPU until the point is reached. That is simple and works well for tools, tests, and shutdown, but in a frame loop it throws away CPU/GPU overlap.
  • RI::isReached(queue, point) answers at once, without blocking. Use it to check whether old resources can be freed yet, and do other work if not.
// Do other CPU work while the GPU runs; isReached never blocks.
uint32 polls = 0;
while (!RI::isReached(queue, again)) {
    ++polls;
}
std::printf("reached after %u polls (point %llu)\n", polls, static_cast<unsigned long long>(again.value));

Both may be called from any thread.

The one rule

Remember the point of the last submission that uses something. Touch that something only once that point is reached.

RI has no frame concept and destroys objects immediately: it does not keep track of what the GPU is using. That bookkeeping is yours (or a helper's). The rule covers:

You want to... Wait for the point of...
read results on the CPU (readback memory, queries) the submission that wrote them.
destroy a buffer, texture, pipeline or heap, or free memory the last submission that used it.
overwrite a descriptor slot the last submission that may read the old descriptor.
write new data into an upload buffer the GPU reads the last submission that reads the old data.
reset, re-record or destroy a command list that list's own submission (below).

"Uses" is about submissions, not recording. A buffer used in a list that was recorded but never submitted is not in use by the GPU.

Example: read a result

const RI::TimelinePoint done = RI::submit(queue, cmd); // the GPU copies into `result`
// result.mapped holds garbage here: the GPU may not have started.
RI::wait(queue, done);
// Now it holds the GPU's writes.

Example: destroy a buffer you stopped using

Suppose a buffer is used in frame 10 and not after. Store frame 10's point with it, and destroy it later, once that point is reached, without stalling:

struct Retired {
    RI::Buffer buffer;
    RI::TimelinePoint lastUse;
};
std::vector<Retired> retired;

retired.push_back({oldBuffer, frame10Point}); // stop using it, but do not destroy yet

// Each frame: destroy whatever the GPU is done with.
std::erase_if(retired, [&](Retired &r) {
    if (!RI::isReached(queue, r.lastUse)) {
        return false;
    }
    RI::destroyBuffer(device, r.buffer);
    return true;
});

Since points only grow, the oldest entries are reached first: in a list kept in order you can stop at the first one that is not reached.

Frames in flight

To keep the GPU busy, the CPU records frame n + 1 while the GPU runs frame n. Anything the CPU writes every frame (a command list, an upload buffer of per-frame constants) then needs one copy per frame in flight: copy i is touched again only once the point of the frame that last used it is reached. With two copies, the CPU waits only when it gets two frames ahead. The frame ring helper does exactly this.

Helpers that do the bookkeeping

The rule is simple but repetitive. The helpers take points so you do not have to track them:

Helper What it does with points
Frame ring endFrame returns the frame's point; beginFrame waits for it only when it reuses that frame's list.
Slot allocator releaseSlot(slots, slot, lastUse): the slot is handed out again only once lastUse is reached.
Memory allocator release(allocator, allocation, lastUse): the range is reused only once lastUse is reached.
// Free the slot once the last frame that may read it is done.
RI::Helpers::releaseSlot(slots, slot, lastFrame);

Things that trip people up

  • A point belongs to one queue. Ask about it on the queue whose submit returned it. In this version there is only device.graphicsQueue; with more queues, each will have its own counter, and {5} on one queue says nothing about another.
  • Do not make up points. Only use points that submit returned (or {0}). Waiting for a value no submission will ever signal blocks forever: wait has no timeout in this version.
  • Calling wait right after every submit is correct, but slow. It is the easy way to start; switch to keeping points and isReached (or the frame ring) when the CPU and GPU should overlap.
  • A swapchain image cycle is not frames in flight: acquire and present synchronise the images, not your own per-frame data. Your own per-frame data still needs timeline points.
  • Shutting down: before destroying anything, wait for the last point you got (the latest one covers all earlier ones), then destroy in any order the objects themselves allow.
  • A lost device (driver crash, GPU reset) makes wait and isReached report a device lost error through the error channel.

Command lists are submitted once, then reused

A command list has one life cycle:

  1. cmdBegin, record commands, cmdEnd;
  2. submit it once, keep its timeline point;
  3. when the point is reached, resetCommandList and record it again (or destroy it).
// The list's timeline point is reached, so it may be reset and recorded again.
RI::resetCommandList(cmd);
RI::cmdBegin(cmd);
RI::cmdSetHeap(cmd, heap);
RI::cmdSetPipeline(cmd, pipeline);
RI::Helpers::cmdSetRootData(cmd, Root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 2.0f, .count = kCount});
RI::cmdDispatch(cmd, (kCount + 63) / 64, 1, 1);
RI::cmdEnd(cmd);
const RI::TimelinePoint again = RI::submit(queue, cmd);

There is no resubmission of a recorded list in this version. Each command list has its own native command memory (a Vulkan command pool, a D3D12 command allocator), so resetting one list never disturbs another. Recording happens on one thread in this version, and RI objects are not thread-safe: only the calls on the any-thread list—including wait and isReached—may be called from other threads.

This is the one case RI checks for you: in validation builds, resetting or destroying a list the GPU may still be executing is a programmer error: resetting a command list the GPU may still be executing: wait for its timeline point (value 3) first; the queue has reached 2. For buffers, textures, descriptors and the rest, RI does not check the rule; the native debug layers catch some of these mistakes, not all.

The same in native code

Natively, the timeline is a Vulkan timeline semaphore and a D3D12 fence: both are a 64-bit counter the GPU raises, as above. RI creates one per queue, picks the next value at each submit, and gives it back to you as a TimelinePoint.

RI::Queue &queue = device.graphicsQueue;
const RI::TimelinePoint done = RI::submit(queue, cmd);
RI::wait(queue, done); // blocks until the GPU has finished this submission
// A timeline semaphore: a 64-bit counter the GPU raises as work completes.
const VkSemaphoreTypeCreateInfo timelineType{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO,
                                             .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE,
                                             .initialValue = 0};
const VkSemaphoreCreateInfo semaphoreInfo{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = &timelineType};
VkSemaphore timeline = VK_NULL_HANDLE;
check(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &timeline), "vkCreateSemaphore");
uint64_t lastSignaled = 0;
// Submit, asking the GPU to raise the counter to the next value when done.
const uint64_t done = ++lastSignaled;
const VkCommandBufferSubmitInfo commandSubmit{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO,
                                              .commandBuffer = cmd};
const VkSemaphoreSubmitInfo signal{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO,
                                   .semaphore = timeline,
                                   .value = done,
                                   .stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT};
const VkSubmitInfo2 submitInfo{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2,
                               .commandBufferInfoCount = 1,
                               .pCommandBufferInfos = &commandSubmit,
                               .signalSemaphoreInfoCount = 1,
                               .pSignalSemaphoreInfos = &signal};
check(vkQueueSubmit2(queue, 1, &submitInfo, VK_NULL_HANDLE), "vkQueueSubmit2");
const VkSemaphoreWaitInfo waitInfo{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO,
                                   .semaphoreCount = 1,
                                   .pSemaphores = &timeline,
                                   .pValues = &done};
check(vkWaitSemaphores(device, &waitInfo, UINT64_MAX), "vkWaitSemaphores");

What to watch for: binary semaphores and fences (VkFence) are the older tools; a timeline semaphore replaces both for this use, and needs the timelineSemaphore feature (core in Vulkan 1.2).

// A fence: a 64-bit counter the queue raises as work completes.
ComPtr<ID3D12Fence> fence;
check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "CreateFence");
UINT64 lastSignaled = 0;
ID3D12CommandList *lists[] = {cmd.Get()};
queue->ExecuteCommandLists(1, lists);
const UINT64 done = ++lastSignaled;
check(queue->Signal(fence.Get(), done), "Signal"); // raised when the work before it is done
if (fence->GetCompletedValue() < done) {
    // A null event: the call blocks until the fence reaches the value.
    check(fence->SetEventOnCompletion(done, nullptr), "SetEventOnCompletion");
}

What to watch for: Signal is a separate queue call after ExecuteCommandLists. A removed device reports UINT64_MAX on every fence; RI checks for it and reports a device lost error.