Example: VulkanExamples/p29-threads
Vulkan спроєктований для паралельного запису команд — але лише якщо
ви поважаєте одне правило: VkCommandPool не є потокобезпечним.
Кожен allocate, begin, record, reset на пулі має бути
зовні синхронізований. Дешевий спосіб це задовольнити: один пул
на потік (чи на потік на кадр). Потоки записують у буфери свого
пулу з нульовим локуванням; один первинний буфер викликає
vkCmdExecuteCommands, щоб відтворити їхні
вторинні
всередині одного рендерингу.
Форма
// setup (main thread): one pool per worker
for (int i = 0; i < N; ++i)
pools[i] = device->createCommandPoolUnique(
{eResetCommandBuffer, queueFamily});
// workers: allocate + record from YOUR pool only
std::thread t([&, i] {
auto sec = device->allocateCommandBuffersUnique(
{pools[i].get(), eSecondary, 1}).front();
sec->begin(beginInfo); // inheritance + eRenderPassContinue
/* bind, pushConstants, draw */
sec->end();
});
// join, then on the main thread:
primary.executeCommands(sec.get()); // inside beginRendering
Що ділиться, а що ні
| Об’єкт | Потокобезпечний для спільного? |
|---|---|
VkDevice | так — усі виклики створення неявно синхронізовані |
VkCommandPool | ні — один на потік |
VkCommandBuffer | ні — один буфер, один записувач за раз |
VkPipeline, VkPipelineLayout | так — pipeline незмінні після створення |
VkQueue::submit | ні — один потік подає (чи серіалізуйте самі) |
Потоки запису ніколи не торкаються vk.queue — подання лишається
на головному потоці, що саме там, де модель володіння чергою його
хоче.
Як це НЕ робити
- Не діліть пул з м’ютексом навколо begin/end — воно працює, але серіалізує дорогу частину (запис), зводячи суть нанівець.
- Не дозволяйте вторинному пережити його кадр — первинний, що виконав його, може ще бути в польоті; списуйте пули на кадр чи кільцюйте їх фенсами (правила кадрів-у-польоті стосуються також ресурсів, на які посилаються вторинні).
- Не забувайте inheritance-info + динамічний стан — вторинні
все ще мають декларувати
eRenderPassContinueзVkCommandBufferInheritanceRenderingInfo, і вони все ще не наслідують viewport/scissor (див. пост про вторинні буфери — цей приклад встановлює їх на вторинний).
Збірка та запуск
g++ -std=c++23 -O2 -pthread main.cpp -o app -lvulkan -lglfw -lshaderc
./app --headless out.ppm && python3 check.py out.ppmЧотири робочі потоки кожен записує одну кольорову смугу; первинний
відтворює всі чотири вторинні в одному рендерингу. check.py
асертить і рядки логу ([thread i] recorded), і вивід пікселів.
#!/usr/bin/env python3
# SPDX-License-Identifier: CC0-1.0
# check.py — verify 4 thread-recorded secondaries rendered their
# strips (R/G/B/W left-to-right) AND the log proves the recording
# ran on worker threads.
import re
import subprocess
import sys
def read_ppm(path):
d = open(path, "rb").read()
hdr, data = d.split(b"255\n", 1)
toks = hdr.split()
w, h = int(toks[1]), int(toks[2])
assert len(data) == w * h * 3
return w, h, data
def px(d, w, x, y):
i = (y * w + x) * 3
return tuple(d[i:i + 3])
def main():
path = sys.argv[1] if len(sys.argv) > 1 else "out.ppm"
out = subprocess.run(["./app", "--headless", path],
capture_output=True, text=True)
assert out.returncode == 0, out.stderr
print(out.stdout, end="")
# all 4 workers recorded
for i in range(4):
assert f"[thread {i}] recorded secondary" in out.stdout
w, h, d = read_ppm(path)
assert (w, h) == (384, 384)
y = h // 2
# strips centered at NDC x = -0.75,-0.25,+0.25,+0.75
# -> px x = (1+x)*192: 24, 144, 240, 336
c0 = px(d, w, 48, y)
c1 = px(d, w, 144, y)
c2 = px(d, w, 240, y)
c3 = px(d, w, 336, y)
print("strips:", c0, c1, c2, c3)
assert c0[0] > 150 and c0[1] < 120, c0
assert c1[1] > 150 and c1[0] < 120, c1
assert c2[2] > 150 and c2[0] < 120, c2
assert all(c > 200 for c in c3), c3
print("OK: 4 secondaries recorded on worker threads, replayed "
"in one rendering")
if __name__ == "__main__":
main()[thread 0] recorded secondary
[thread 1] recorded secondary
[thread 3] recorded secondary
[thread 2] recorded secondary
strips: (255, 51, 51) (51, 255, 51) (51, 51, 255) (255, 255, 255)
OK: 4 secondaries recorded on worker threads, replayed in one renderingПовний вихідний код
// SPDX-License-Identifier: CC0-1.0
//
// Multi-threaded command recording: each thread gets its OWN
// VkCommandPool (pools are externally synchronized — never share
// one across threads) and records a SECONDARY buffer; the main
// thread's primary calls vkCmdExecuteCommands once. This is the
// real version of the secondary-buffer post.
//
// Demo: 4 threads each record a secondary drawing one column of a
// 4x1 strip (R/G/B/W) — logged with thread ids to prove the
// recording really ran on different threads.
//
// ./app --headless o.ppm one frame -> PPM for check.py
// ./app windowed
//
// Build: g++ -std=c++23 -O2 main.cpp -o app -lvulkan -lglfw -lshaderc -pthread
#include "vkmini.hpp"
#include <GLFW/glfw3.h>
#include <thread>
static const char* kVert = R"GLSL(
#version 460
layout(push_constant) uniform Push { vec3 col; vec2 ofs; } pc;
layout(location = 0) out vec3 vColor;
void main() {
vec2 p[6] = vec2[](vec2(-0.5,-0.5), vec2(0.5,-0.5), vec2(0.5,0.5),
vec2(-0.5,-0.5), vec2(0.5,0.5), vec2(-0.5,0.5));
gl_Position = vec4(p[gl_VertexIndex] * vec2(0.22, 0.8) + pc.ofs,
0, 1);
vColor = pc.col;
}
)GLSL";
static const char* kFrag = R"GLSL(
#version 460
layout(location = 0) in vec3 vColor;
layout(location = 0) out vec4 outColor;
void main() { outColor = vec4(vColor, 1.0); }
)GLSL";
struct Push {
float col[3];
float pad;
float ofs[2];
};
int main(int argc, char** argv) {
bool headless = argc > 1 && std::string(argv[1]) == "--headless";
const char* ppmOut = argc > 2 ? argv[2] : "out.ppm";
(void)headless;
vkmini::Vk vk;
vk.createInstance({});
vk.pickPhysicalDevice();
vk.createDevice({});
vk::Format fmt = vk::Format::eR8G8B8A8Unorm;
auto vs = vk.shader(kVert, shaderc_vertex_shader, "s.vert");
auto fs = vk.shader(kFrag, shaderc_fragment_shader, "s.frag");
vk::PipelineShaderStageCreateInfo stages[2];
stages[0].setStage(vk::ShaderStageFlagBits::eVertex)
.setModule(vs.get())
.setPName("main");
stages[1].setStage(vk::ShaderStageFlagBits::eFragment)
.setModule(fs.get())
.setPName("main");
vk::PipelineVertexInputStateCreateInfo vin{};
vk::PipelineInputAssemblyStateCreateInfo ia{};
ia.setTopology(vk::PrimitiveTopology::eTriangleList);
vk::PipelineViewportStateCreateInfo vp{};
vp.setViewportCount(1).setScissorCount(1);
std::array dynStates{vk::DynamicState::eViewport,
vk::DynamicState::eScissor};
vk::PipelineDynamicStateCreateInfo dyn{};
dyn.setDynamicStates(dynStates);
vk::PipelineRasterizationStateCreateInfo rs{};
rs.setPolygonMode(vk::PolygonMode::eFill)
.setCullMode(vk::CullModeFlagBits::eNone)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setLineWidth(1.0f);
vk::PipelineMultisampleStateCreateInfo ms{};
ms.setRasterizationSamples(vk::SampleCountFlagBits::e1);
vk::PipelineColorBlendAttachmentState cb{};
cb.setColorWriteMask(
vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
vk::PipelineColorBlendStateCreateInfo blend{};
blend.setAttachments(cb);
vk::PushConstantRange pcr{};
pcr.setStageFlags(vk::ShaderStageFlagBits::eVertex)
.setSize(sizeof(Push));
vk::PipelineLayoutCreateInfo plci{};
plci.setPushConstantRanges(pcr);
auto layout = vk.device->createPipelineLayoutUnique(plci);
vk::PipelineRenderingCreateInfo rendering{};
rendering.setColorAttachmentFormats(fmt);
vk::GraphicsPipelineCreateInfo gi{};
gi.setStages(stages)
.setPVertexInputState(&vin)
.setPInputAssemblyState(&ia)
.setPViewportState(&vp)
.setPDynamicState(&dyn)
.setPRasterizationState(&rs)
.setPMultisampleState(&ms)
.setPColorBlendState(&blend)
.setLayout(layout.get())
.setPNext(&rendering);
auto pres = vk.device->createGraphicsPipelineUnique({}, gi);
if (pres.result != vk::Result::eSuccess)
throw std::runtime_error("pipeline failed");
auto pipe = std::move(pres.value);
vkmini::Headless hl;
hl.init(vk, 384, 384);
// ---- 4 threads, each its OWN pool + secondary -----------------
const float cols[4][3] = {{1, .2f, .2f}, {.2f, 1, .2f},
{.2f, .2f, 1}, {1, 1, 1}};
std::array<vk::UniqueCommandPool, 4> pools;
std::array<vk::UniqueCommandBuffer, 4> secs;
std::array<std::thread, 4> threads;
for (int i = 0; i < 4; ++i) {
pools[i] = vk.device->createCommandPoolUnique(
{vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
vk.qfam});
threads[i] = std::thread([&, i] {
secs[i] = std::move(
vk.device->allocateCommandBuffersUnique(
{pools[i].get(),
vk::CommandBufferLevel::eSecondary, 1})
.front());
vk::CommandBuffer c = secs[i].get();
vk::CommandBufferInheritanceRenderingInfo inhr{};
vk::Format f = fmt;
inhr.setColorAttachmentFormats(f);
vk::CommandBufferInheritanceInfo inh{};
inh.setPNext(&inhr);
vk::CommandBufferBeginInfo bi{};
bi.setFlags(
vk::CommandBufferUsageFlagBits::eRenderPassContinue)
.setPInheritanceInfo(&inh);
c.begin(bi);
vk::Viewport v{0, 0, float(hl.extent.width),
float(hl.extent.height), 0.f, 1.f};
c.setViewport(0, v);
vk::Rect2D sc{{0, 0}, hl.extent};
c.setScissor(0, sc);
c.bindPipeline(vk::PipelineBindPoint::eGraphics,
pipe.get());
Push p{{cols[i][0], cols[i][1], cols[i][2]}, 0.f,
{-0.75f + 0.5f * float(i), 0.f}};
c.pushConstants(layout.get(),
vk::ShaderStageFlagBits::eVertex, 0,
sizeof(Push), &p);
c.draw(6, 1, 0, 0);
c.end();
printf("[thread %d] recorded secondary\n", i);
});
}
for (auto& t : threads)
t.join();
hl.render(
vk::ImageLayout::eColorAttachmentOptimal,
[&](vk::CommandBuffer c) {
vk::RenderingAttachmentInfo att{};
att.setImageView(hl.color.view.get())
.setImageLayout(
vk::ImageLayout::eColorAttachmentOptimal)
.setLoadOp(vk::AttachmentLoadOp::eClear)
.setStoreOp(vk::AttachmentStoreOp::eStore)
.setClearValue(vk::ClearValue{vk::ClearColorValue{
std::array{0.05f, 0.05f, 0.08f, 1.f}}});
vk::RenderingInfo ri{};
ri.setRenderArea({{0, 0}, hl.extent})
.setLayerCount(1)
.setColorAttachments(att);
c.beginRendering(ri);
for (auto& s : secs)
c.executeCommands(s.get());
c.endRendering();
});
hl.savePpm(ppmOut);
printf("wrote %s\n", ppmOut);
return 0;
}Увесь вихідний код цієї серії випущено під CC0 1.0 Universal (CC0-1.0) — передача в суспільне надбання, атрибуція не потрібна.