chapter two

2 Your first parallel program

 

This chapter covers

  • The structure of a parallel CUDA program
  • How to write a kernel function with __global__
  • How to launch parallel work with <<<…>>>
  • How threads use threadIdx to identify themselves
  • How the hardware runs your threads: warps, SMs, and CUDA cores
  • How to transfer data between the host (CPU) and the device (GPU)

You met the grading room in Chapter 1: one teacher, a stack of 1,000 worksheets, and 1,000 students who could each grade one. In this chapter the analogy stops being a picture and becomes a program. By the end, you’ll have written the “grade the sheet in front of you” instruction in CUDA and submitted your first solutions to swforces.com. All you need on hand is your swforces.com account from Chapter 1 and basic C: functions, loops, and a little comfort with pointers (malloc and free will make a brief appearance).

Hello, Parallel World!

Every programmer starts with “Hello, World.” Ours has a twist: instead of printing the message once, we’ll have eight threads print it at the same time. But what is a thread? Picture those 1,000 students again: each student is one thread, a single worker that runs your code on its own small slice of the work. A parallel program launches many threads at once, and every one of them runs the same code independently.

The headers: plugging in the toolkit

The kernel function: a function that runs in parallel

The launch syntax: fire those threads!

Synchronization: you have to wait!

Each thread has its own job

Meet threadIdx

How the hardware runs your threads: warps and SMs

Squaring an array

The function signature

Thread index

Bounds check

The actual work

Moving data: CPU to GPU and back

Step 1: Allocate device memory (set up desks in the grading room)

Step 2: Copy Host to Device (carry the worksheets to the students)

Step 3: Launch kernel (let the students grade)

Step 4: Copy Device to Host (collect the graded worksheets)

Step 5: Free memory (clear the desks out of the room)

Common Mistakes

Mistake #1: Forgetting to Synchronize

Mistake #2: Copying Data the Wrong Way

Mistake #3: Missing Bounds Check

Summary