0Pricing
Learn Rust Coding · 강의

스레드 생성하기

코드를 동시에 실행해 보세요.

스레드 생성하기은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a Thread?

A thread lets your program run code concurrently. The operating system can schedule multiple threads, so work can overlap.

Rust's standard library exposes threads through the std::thread module. These are native OS threads, sometimes called 1:1 threads.

In this lesson you will learn to start new threads and control how they run.

Spawning with thread::spawn

You create a new thread by calling thread::spawn and passing it a closure. The closure holds the code the new thread will run.

The call returns immediately with a JoinHandle, while the spawned thread runs in the background.

use std::thread;

fn main() {
    thread::spawn(|| {
        println!("hello from a thread");
    });
    println!("hello from main");
}

Main May Finish First

When main returns, the whole process ends, even if spawned threads are still running.

So the program above might print only the main message. The background thread may not get a chance to run before the process exits.

We need a way to wait for threads to finish.

Waiting with join

The JoinHandle returned by spawn has a join method. Calling it blocks the current thread until the spawned thread finishes.

This guarantees the spawned thread runs to completion before main continues.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("worker done");
    });
    handle.join().unwrap();
    println!("main done");
}

Interleaving Output

When two threads run at once, their output can interleave in unpredictable ways. The OS decides the schedule.

Running the same program twice may produce different orderings. Never rely on a specific order without synchronization.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..4 {
            println!("thread: {}", i);
        }
    });
    for i in 1..4 {
        println!("main: {}", i);
    }
    handle.join().unwrap();
}

Pausing with sleep

You can pause a thread with thread::sleep, which takes a Duration. This yields the CPU so other threads can make progress.

Sleeping is useful in examples to make interleaving more visible, but avoid it for real synchronization.

use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..4 {
            println!("spawned: {}", i);
            thread::sleep(Duration::from_millis(1));
        }
    });
    thread::sleep(Duration::from_millis(10));
}

Spawning Many Threads

You can spawn several threads in a loop and collect their handles into a vector.

Later you iterate the vector and join each handle, ensuring every thread completes before the program ends.

use std::thread;

fn main() {
    let mut handles = vec![];
    for id in 0..3 {
        let h = thread::spawn(move || {
            println!("thread {}", id);
        });
        handles.push(h);
    }
    for h in handles {
        h.join().unwrap();
    }
}

Naming Threads with Builder

The thread::Builder type lets you configure a thread before spawning. You can set a name and a stack size.

Named threads make panic messages and debugging easier to read.

use std::thread;

fn main() {
    let h = thread::Builder::new()
        .name("worker".into())
        .spawn(|| {
            println!("running in named thread");
        })
        .unwrap();
    h.join().unwrap();
}

Panics Stay in the Thread

If a spawned thread panics, it does not crash the whole program by default. The panic is contained in that thread.

When you call join on a panicked thread, you get an Err. This lets the parent detect the failure.

use std::thread;

fn main() {
    let h = thread::spawn(|| {
        panic!("boom");
    });
    let result = h.join();
    println!("joined, is_err = {}", result.is_err());
}

Current Thread Info

You can inspect the running thread with thread::current. It returns a handle whose name method gives the optional thread name.

The main thread is also a real thread, usually named main.

use std::thread;

fn main() {
    let current = thread::current();
    println!("name: {:?}", current.name());
}

Returning Values from Threads

The closure passed to spawn can return a value. That value comes back wrapped in Ok when you call join.

This is a simple way to compute something on another thread and read the result later.

use std::thread;

fn main() {
    let h = thread::spawn(|| {
        let sum: i32 = (1..=10).sum();
        sum
    });
    let total = h.join().unwrap();
    println!("total = {}", total);
}

Quick Check

Test your understanding of spawning threads.

Recap

You learned to start threads with thread::spawn and a closure, which returns a JoinHandle.

Calling join waits for completion and surfaces the return value or a panic. Output between threads can interleave unpredictably, and the Builder lets you name threads.

Next you will see how to move data into the threads you spawn.

자주 묻는 질문

“스레드 생성하기” 강의는 무료인가요?

네 — “스레드 생성하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“스레드 생성하기”에서 뭘 배우나요?

코드를 동시에 실행해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“스레드 생성하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 스레드 생성하기
  2. 스레드로 데이터 이동하기
  3. Arc와 Mutex로 공유하기
  4. 결과 결합하고 수집하기
← Learn Rust Coding(으)로 돌아가기