Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Programming Concurrency on GPUs with Rust Examine, Run, and Measure GPU Workloads Using CUDA, Streams, and Async Pipelines Zyle Kot GitforGits 2026-09 Copyright 2026 by GitforGits
Page
3
Programming Concurrency on GPUs with Rust Programming Concurrency on GPUs with Rust Examine, Run, and Measure GPU Workloads Using CUDA, Streams, and Async Pipelines Zyle Kot Copyright © 2026 by GitforGits All rights reserved. This book is protected under copyright laws and no part of it may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without the prior written permission of the publisher. Any unauthorized reproduction, distribution, or transmission of this work may result in civil and criminal penalties and will be dealt with in the respective jurisdiction at anywhere in India, in accordance with the applicable copyright laws. Published by: GitforGits www.gitforgits.com Printed in India First Printing: September 2026 ISBN: 978-81-17136-05-8
Page
4
Cover Design by: Kitten Publishing Disclaimer: This book, including all its text, diagrams, and illustrations, is an original work developed for educational and informational purposes. The content is not affiliated with, endorsed by, or sponsored by or any other company, brand, or entity referenced within. All brand names, product names, and trademarks mentioned are the property of their respective owners and are used in a descriptive, educational context only. Every effort has been made to ensure that no copyrighted or trademarked material has been copied or misused in this book. All diagrams and illustrations that are not original have been used with proper attribution and credit to their respective sources. If you believe that any content in this book infringes upon your copyright or trademark, please contact us immediately at support@gitforgits.com. Upon notification, corrective action will be taken promptly. Prologue I have spent more of my life waiting for a profiler to tell me something I did not already suspect, and I have spent more of my life staring at a computer screen than I would like to admit. This rarely happens. Eventually, you stop being surprised by the story on a GPU timeline and start to become annoyed by it instead, because it's almost always the same story. The story goes like this. A kernel is written. The kernel is fine. In fact, it's usually better than fine, because people who write GPU kernels tend to care about their work, and they'll happily remove an instruction from an inner loop at midnight. Then they run the program and it's slow. They assume the kernel is to blame and go back to shave off another instruction. The timeline shows that the GPU finished its real work in a handful of milliseconds and then did nothing, waiting for the next copy, allocation or time that the host remembered its existence.
Page
5
Yet the device is not slow. The device is starving. We built a machine with thousands of cores and then fed it through a straw. That's why I wrote this book. I'm tired of watching good engineers lose that fight. The tools to win it have finally matured in a language I trust. There's a trade-off with concurrency, though. It gives you speed but also introduces bugs that only appear once in a thousand runs and disappear when you look directly at them. Fortunately, Rust rewrites that bargain. A borrow checker that prevents two writers from accessing the same buffer is worth more than a week of code review, and the GPU crates we use extend this discipline to the device itself. I have shipped enough racy CUDA in my time to know exactly what that is worth. Therefore, we are going to do this properly. We will work in pure Rust, with no C++ shim or Python wrapper. We will build one small program that grows to cover the whole book. It begins as a loop that any of us could have written on a bad day. After gaining a kernel, it learns to stop waiting, grows streams and pinned memory, and ends as a pipeline fed by parallel producers through bounded channels. The device is busy almost every millisecond. We measure at every step, because a claim without a number is just a hope. We also check the answer at every step against something we trust, because being fast but wrong is the most expensive outcome. While you don't need to be a CUDA veteran or a Rust wizard, you do need the one instinct this whole discipline rests on. What you need is the one instinct on which this whole discipline rests. When something is slow, you don't guess. You open the timeline and ask who is waiting and for what. It's important to learn to ask this question effectively, because the rest of this book is detailing. --Zyle Kot Content
Page
6
Preface The bottleneck is not your kernel. In fact, it almost never is. After spending enough time in Nsight, the way you read a timeline becomes as intuitive as a mechanic listening to an engine. The same faults keep cropping up, such as a GPU with thousands of cores sitting idle behind a blocking copy, a single default stream or a host thread frozen at a synchronisation point that was never necessary. This book is about identifying that fault early and eliminating it. Designed for programming professionals, this book is written for GPU developers, Rust engineers and AI practitioners who want their devices to be busy, not just correct. Our approach is to stay in pure Rust throughout, using cuda-oxide for SIMT kernels and cutile-rs for the tile model. We also rely heavily on the type system to ensure that data races fail at compile time rather than at 3 AM during production. We will overlap transfers with compute using streams and pinned memory, build a staging ring that pipelines every stage and feed the GPU through Tokio producers with bounded-channel backpressure. Each technique is profiled, verified against a CPU reference and measured. In this book you will learn to: Profile before you optimise, and let Nsight Systems show you who is actually waiting. Write SIMT kernels in pure Rust where data races fail at compile time. Treat default stream as the enemy of overlap, and fork your own. Overlap copies with compute using pinned memory and a staging ring.
Page
7
Reach for reduction ladder instead of atomics when summing on the device. Express element-wise work as tile kernels, and let compiler map the hardware. Keep the GPU fed with Tokio producers and bounded-channel backpressure. Verify every kernel against CPU reference before you trust its timing. Weigh throughput against latency, since tuning for one quietly taxes the other. Know when to stop, because past a point concurrency only adds bookkeeping.
Page
8
GitforGits Prerequisites If you're a programmer looking for a hands-on guide to GPU programming, Rust techniques and AI principles, this book is for you. It's designed to help you make the most of your device's processing power. Codes Usage Are you in need of some helpful code examples to assist you in your programming and documentation? Look no further! Our book offers a wealth of supplemental material, including code examples and exercises. This book is here to help you get your job done, and you also have our permission to use the example code in your programs and documentation. However, please note that if you are reproducing a significant portion of the code, we do require you to contact us for permission. But don't worry, using several chunks of code from this book in your program or answering a question by citing our book and quoting example code does not require permission. But if you do choose to give credit, an attribution typically includes the title, author, publisher, and ISBN. For example, "Programming Concurrency on GPUs with Rust by Zyle Kot". If you are unsure whether your intended use of the code examples falls under fair use or the permissions outlined above, please do not hesitate to reach out to us at support@gitforgits.com. We are happy to assist and clarify any concerns.
Page
9
Acknowledgement I owe a tremendous debt of gratitude to GitforGits, for their unflagging enthusiasm and wise counsel throughout the entire process of writing this book. Their knowledge and careful editing helped make sure the piece was useful for people of all reading levels and comprehension skills. In addition, I'd like to thank everyone involved in the publishing process for their efforts in making this book a reality. Their efforts, from copyediting to advertising, made the project what it is today. Finally, I'd like to express my gratitude to everyone who has shown me unconditional love and encouragement throughout my life. Their support was crucial to the completion of this book. I appreciate your help with this endeavour and your continued interest in my career.
Page
10
Chapter 1: Rust’s Threads, Timing and Ownership Before a single kernel runs on the GPU, we need a clear picture of what concurrency really means, and this opening chapter builds that foundation for everything that follows. To start, we separate concurrency from parallelism, two words that people often use as if they meant the same thing. After that, we look at why waiting quietly wastes computing power, even in programs that produce perfectly correct results. With those ideas in place, we move to our first Rust threads and learn to measure their speed honestly. Along the way, we see how Rust ownership and borrowing act as guardrails, because they quietly stop many concurrency mistakes before our program ever runs at all. We also begin pixelflow, the small image program that grows with us throughout the book. Finally, we prepare a Linux workspace with the NVIDIA driver, the CUDA toolkit and the cudarc crate. By the close of the chapter, our own Rust code will greet the GPU by name. Separating Concurrency from Parallelism Concurrency as Task Switching At its heart, concurrency is about structure rather than speed. A concurrent program holds several tasks in progress during the same stretch of time, even if only one of them moves at any given instant. For a homely picture, we can think of a single cook who prepares breakfast. The cook starts the kettle, then slices bread while the water heats, and then turns back to pour the tea. Only one pair of hands works at a time. Still, three dishes make progress together, because the cook never stands idle while something else cooks on its own.
Page
11
In a program, those dishes become tasks such as a file read, a network request or an image to process. So, a concurrent design lets the program switch to other useful work whenever one task must pause. That key word is pause. Whenever a task waits for something outside itself, a well-structured program picks up another task instead of freezing. In this sense, concurrency is a way of organising work so that waiting never blocks everything else. It says nothing yet about how many workers actually run at once, and that question belongs to parallelism. Parallelism as Simultaneous Work By contrast, parallelism means that several pieces of work truly run at the same instant. To achieve that, we need more than one worker, such as several CPU cores or the thousands of small cores inside a GPU. If we return to our kitchen, parallelism arrives when a second cook joins the first. Now the toast and the tea can progress at exactly the same moment. At no point does either cook must switch back and forth. As a result, the breakfast is ready sooner, provided the two cooks do not keep reaching for the same knife. That final condition matters more than it first appears. Such parallel workers only help when their work can be split into pieces that do not interfere with one another. Moreover, the two ideas combine quite naturally in practice. A program can be concurrent without being parallel, as our single cook shows, and it can also be both at once. In this book, we care about both qualities together, because a GPU gives us massive parallelism, while good concurrency keeps that parallel hardware fed and busy. The timeline below places the two ideas side by side.
Page
12
Figure 1.1: Concurrency vs. Parallelism When we read the two tracks together, the distinction becomes concrete. The single cook is never idle, yet breakfast still fills the whole stretch of time, because one pair of hands can only move to one task at a time. The second kitchen finishes sooner only because a second worker joined. So, concurrency rearranges waiting, while parallelism adds workers, and we keep that difference in view for the rest of this book. Cost of Waiting Calculating Idle Time Every program spends part of its life waiting. It may wait for a disk to return data, for memory to be copied, or for another component to finish its share of work. Each individual wait often looks harmless, perhaps a few milliseconds at most. However, those milliseconds repeat inside loops that run thousands of times. Over a full batch of images, the small pauses quietly add up to seconds, and sometimes to minutes. The program still returns correct results, so nothing looks wrong on the surface. Only a careful measurement shows how much of the running time went into standing still.
Page
13
During those pauses, the hardware we paid for sits unused. A modern workstation may offer eight or more CPU cores and a GPU with thousands of cores of its own. Yet a program that waits on one step at a time uses only a thin slice of that capacity. In a sense, we end up renting a large delivery van and then carrying one parcel per trip. The van is not slow at all. Instead, our plan for loading it wastes most of its space, and the fix lies in the plan rather than in the vehicle. Common Waiting Points In GPU work, most waiting falls into three familiar places. The first is data movement, because images must travel between CPU memory and GPU memory before and after any computation. The second is synchronisation, where one side stops and waits for the other to confirm that its work is done. Lastly, the third is preparation, where the CPU decodes, resizes or saves files while the GPU has nothing to do. As we will see, each of these waits has its own remedy. Across this book, we meet those remedies one at a time, always with a measurement beside them. For now, it is enough to recognise these waiting spots whenever we read a program. A useful habit is to ask one simple question about every line that touches the GPU. That question is whether the line returns at once or holds the CPU until something finishes elsewhere. Once we start asking that question, hidden waits become much easier to spot. That habit also changes how we judge speed, since a fast program is often just a program that waits less. With this idea settled, we can turn to real code and start with ordinary CPU threads in Rust scripts. Working with Rust Threads Preparing Rust Toolchain
Page
14
To run any code at all, we first need the Rust toolchain on our Linux machine. The official installer, rustup, places the compiler, the cargo build tool and the standard library under our home directory. It also keeps them easy to update later, which matters because the Rust GPU crates move quickly. If Rust is already present, we can simply confirm the version and move ahead. Otherwise, the installer asks a few questions, and the default choices suit this book well. We then reload our shell so that cargo becomes available straight away. With the toolchain in place, we also create the project that stays with us for the rest of the book. We call it pixelflow, and it processes batches of images, one brightness adjustment at a time. In this chapter, the program runs entirely on the CPU, since our goal is to understand threads before the GPU joins in. Its images are synthetic, which means we generate their pixels in code instead of loading real photographs. As a result, we can focus on concurrency without any distraction from image formats or file handling. So here, we will install Rust with rustup and reload the shell: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source "$HOME/.cargo/env" rustc --version After the installer finishes, we will create the pixelflow library project and step inside it: cargo new pixelflow --lib cd pixelflow Spawning First Threads A thread is an independent path of execution inside our program, and each thread can run on its own CPU core. In Rust, threads come directly through std::thread, so we need no extra crate at this stage. When we spawn a thread, we hand it a closure, which is a small piece of code that the new
Page
15
thread runs. The main thread then continues with its own work. At any later point, it can call join on the thread handle and wait for that thread to finish. In this way, join is our first deliberate and visible wait. To keep things gentle, our first program spawns four threads, and each one reports which task it holds. Since the operating system decides when each thread runs, the messages may appear in a different order on every run. That shifting order is not a bug at all. Rather, it is our first real glimpse of concurrency, because the four tasks now progress independently of one another. The program lives in the src/bin folder, where cargo treats every file as a separate runnable binary. This layout keeps each experiment tidy beside the shared library code. We will now create src/bin/hello_threads.rs as below: use std::thread; fn main() { let mut handles = Vec::new(); for task_id in 0..4 { let handle = thread::spawn(move || { println!("task {task_id} running on {:?}", thread::current().id()); handles.push(handle); } for handle in handles { handle.join().expect("thread panicked"); } println!("all tasks finished"); } After that, we can run the new binary with cargo: cargo run --bin hello_threads On this run, the four tasks report in a mixed order before the final message appears:
Page
16
task 1 running on ThreadId(3) task 0 running on ThreadId(2) task 3 running on ThreadId(5) task 2 running on ThreadId(4) all tasks finished Scoped Threads for Batches A plain spawned thread comes with one strict condition. Its closure must own everything it uses, because Rust cannot know how long the thread will live. For image work, that condition feels awkward, since we want every thread to borrow a piece of one shared batch. So, Rust offers scoped threads through thread::scope. Inside a scope, threads may borrow local data, and Rust guarantees that all of them finish before the scope ends. That guarantee lets the borrow checker accept our borrowed data safely, with no copying and no extra ceremony. With scoped threads available, we can now shape the heart of pixelflow. The library needs an Image type, a way to generate a batch of synthetic images and a brighten_cpu function. That function lifts the brightness of every pixel with a gentle gamma curve. The curve involves a little floating-point work per pixel, which gives our CPU something real to chew on. Such honest work matters for this chapter, because a task that finishes in microseconds would hide every timing difference we want to observe. Both the sequential and the threaded programs will reuse this library. In the following, we will replace the contents of src/lib.rs with the shared library code: pub struct Image { pub width: usize, pub height: usize, pub pixels: Vec<u8>, } impl Image { pub fn synthetic(width: usize, height: usize, seed: u8) -> Self {
Page
17
let pixels = (0..width * height * 3) .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)) .collect(); Self { width, height, pixels } } } pub fn synthetic_batch(n: usize, width: usize, height: usize) -> Vec<Image> { (0..n).map(|i| Image::synthetic(width, height, i as u8)).collect() } pub fn brighten_cpu(pixels: &mut [u8], amount: f32) { for p in pixels.iter_mut() { let lifted = (*p as f32 / 255.0).powf(0.8) * 255.0 + amount; *p = lifted.min(255.0) as u8; } } With this library in place, the pixelflow now has everything it needs to create a batch of images and brighten them on the CPU. For the moment, however, we have no idea how long that work takes, or whether our threads actually help. That question deserves a proper answer, so our next step is to put a reliable timer around the work before we draw any conclusions. Measuring Speed with Timers Timing with ‘Instant’ Any claim about speed needs a number behind it, and Rust gives us a dependable clock in std::time::Instant. An Instant records a moment on a monotonic clock, which only ever moves forward. So, a system clock adjustment in the middle of a run cannot corrupt our results. We capture an instant before the work, and we call elapsed on it afterwards. The returned Duration then prints neatly in seconds or milliseconds. This small pattern will follow us through every chapter, since measurement is how we prove that concurrency helps.
Page
18
For any timing to be trustworthy, we must also build in release mode. A debug build skips most compiler optimisations, so it can run many times slower than the real program. Such numbers mislead us about where the time actually goes. For this reason, every measurement in this book uses the -- release flag. We also run each program on an otherwise quiet machine, because a busy browser or a background update can steal cores in the middle of a test. With those two habits, our numbers stay honest and repeatable from one run to the next. To start with, we will create src/bin/cpu_sequential.rs to brighten a batch one image at a time: use std::time::Instant; use pixelflow::{brighten_cpu, synthetic_batch}; fn main() { let mut batch = synthetic_batch(64, 1920, 1080); let start = Instant::now(); for image in batch.iter_mut() { brighten_cpu(&mut image.pixels, 20.0); } println!("sequential: {:.2?}", start.elapsed()); } We then run it in release mode: cargo run --release --bin cpu_sequential When the batch completes, the program reports the time for all sixty-four full HD images: sequential: 2.41s Sequential vs. Threaded Timings
Page
19
With a baseline in hand, we can now spread the same batch across several threads. First, we ask the standard library how many cores are available through available_parallelism. Then, we split the batch into that many groups with chunks_mut, which hands out separate mutable slices of one vector. Inside a thread::scope, each thread brightens its own group of images. Because no two threads ever touch the same image, they never interfere with each other. That simple separation is the whole secret behind safe parallel speed on the CPU. So here, we will create src/bin/cpu_threaded.rs with scoped threads: use std::thread; use std::time::Instant; use pixelflow::{brighten_cpu, synthetic_batch}; fn main() { let mut batch = synthetic_batch(64, 1920, 1080); let workers = thread::available_parallelism().map_or(4, |n| n.get()); let group_size = batch.len().div_ceil(workers); let start = Instant::now(); thread::scope(|s| { for group in batch.chunks_mut(group_size) { s.spawn(move || { for image in group { brighten_cpu(&mut image.pixels, 20.0); } } println!("threaded ({workers} workers): {:.2?}", start.elapsed()); } We can then run the threaded version the same way: cargo run --release --bin cpu_threaded On the same machine, the threaded run reports its worker total and a much shorter time:
Page
20
threaded (8 workers): 318.64ms With both programs run, the comparison tells a clear story. On an eight core machine, the threaded version finishes the same batch in about a third of a second, against 2.41 seconds for the sequential run. That result is close to eight times faster, though never perfectly so. After all, thread start up, memory traffic and the operating system all claim a small share of time. The two screenshots below show the same difference from the outside. Figure 1.2: Sequential Run
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A hands-on guide for Rust developers who want to move beyond CPU threads and learn GPU concurrency by building one small image-processing program from first principles. It suits programmers who already know some Rust and want a practical, profiler-driven path into CUDA-style kernel work.
【Book Arc】
- **Opening (~0%–10%)**: Establishes the mental model — concurrency versus parallelism, why idle waiting wastes hardware, and how Rust ownership acts as a compile-time guardrail. Introduces the running `pixelflow` image library and a Linux/CUDA workspace, ending with Rust "greeting the GPU by name."
- **Early (~10%–32%)**: Moves from CPU threads to the device: comparing CPU and GPU core design, host/device memory separation, the cuda-oxide toolchain, first device buffers, and a first brighten kernel verified against a CPU reference. Closes by exposing GPU idle time as the book's central problem.
- **Middle (~32%–48%)**: Opens the SIMT black box — thread indices, blocks and grids, coverage checks, PPM output for visual verification, and honest timing with stream synchronization. A three-way benchmark (sequential CPU, threaded CPU, GPU round trip) reveals that kernels are fast but data movement dominates.
- **Late (beyond ~48%, per excerpts)**: Begins tackling the round-trip gap: shared-state hazards, lost updates, atomics versus reduction ladders, and GPU-side ownership types like `DisjointSlice`. The excerpts do not cover the remaining chapters in detail.
【Key Takeaways】
- **The kernel is rarely the bottleneck** (Opening): The recurring story is a well-tuned kernel finishing in milliseconds while the GPU idles waiting on copies, allocations, or host attention. Profile the timeline before optimizing instructions.
- **Concurrency is structure, parallelism is speed** (Opening): The book separates the two early, using a single-cook breakfast analogy, so later GPU work rests on a clear vocabulary rather than buzzwords.
- **Ownership is a concurrency guardrail** (Early): Scoped threads and `chunks_mut` let the compiler prove non-overlapping writes at build time; a deliberately racy program simply refuses to compile. This safety model carries onto the device via types like `DisjointSlice`.
- **CPU and GPU are complementary specialists** (Early): A few deep, branch-predicting CPU cores coordinate; thousands of simple GPU cores crunch. The host prepares and dispatches, the device computes — neither finishes alone.
- **SIMT means one function, thousands of copies** (Middle): Each thread maps its index to a pixel, so position-aware effects need only dimensions passed as scalars. Blocks and grids must cover the image, and a coverage check is a cheap safety net.
- **Timing GPU code requires synchronization** (Middle): A launch only queues work; timing without `stream.synchronize` measures nothing. The book insists on separating kernel-only time from full round-trip time.
- **Data movement, not compute, is the enemy** (Middle): Benchmarks show the GPU beating eight CPU cores on kernels alone yet losing on round trip because copies and allocations dominate — the gap the rest of the book targets.
- **Shared totals need atomics or reductions** (Late): A worked lost-update example shows why read-modify-write races corrupt sums, and why `fetch_add` with relaxed ordering fixes correctness before performance tuning begins.
【Reading Tips】
- Deep-read Chapters 1–3; they build the vocabulary (concurrency vs. parallelism, SIMT, host/device split) that everything later assumes. Skim only if you already know CUDA concepts.
- Type the code rather than downloading it — the `pixelflow` library grows incrementally, and the timing comparisons only make sense if your baseline matches the book's.
- Treat the benchmark sections as the spine: whenever a new technique appears, ask whether it shrinks kernel time or round-trip time. That question is the book's organizing logic.
- Watch for the verification habit — every kernel is checked against a CPU reference before timing. Adopt it; it is the most transferable practice in the book.
- The excerpts thin out past the midpoint, so expect the reduction-ladder and backpressure material to require careful reading without much preview here.
【Coverage Limits】
This guide is based on stratified excerpts covering roughly the first half of the book; later chapters on reductions, Tokio-fed pipelines, and throughput/latency trade-offs are only glimpsed through the prologue's summary points, so specifics there are not covered.
Passage locations
Excerpt 1
allocation or time that the host remembered its existence. Reach for reduction ladder instead of atomics when summing on the device. Express element-wise wor...
View in text
Excerpt 2
different stance and refuses to build it at all. The error message may look long at first, yet it names the exact problem, which is two mutable borrows of on...
View in text
Excerpt 3
e GPU on the same batch. Those numbers reveal where the GPU truly shines, and where our program still loses time. SIMT Execution Model Same Instructions acro...
View in text
Excerpt 4
exactly what the coming chapters set out to close. Summary In this chapter, we learned that a SIMT kernel runs as thousands of copies, each working on its ow...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay