0Pricing
Learn Rust Coding · Ders

İş Parçacıkları Oluşturma

Kodu eşzamanlı çalıştırın.

İş Parçacıkları Oluşturma, CoddyKit'te ücretsiz bir Learn Rust Coding dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Learn Rust Coding öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Learn Rust Coding kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“İş Parçacıkları Oluşturma” dersi ücretsiz mi?

Evet — “İş Parçacıkları Oluşturma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Learn Rust Coding kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Learn Rust Coding kursu toplamda 4 dersten oluşur.

“İş Parçacıkları Oluşturma” dersinde ne öğreneceğim?

Kodu eşzamanlı çalıştırın. Learn Rust Coding ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Learn Rust Coding öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Learn Rust Coding, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“İş Parçacıkları Oluşturma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Learn Rust Coding dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Learn Rust Coding dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. İş Parçacıkları Oluşturma
  2. Verileri İş Parçacıklarına Taşıma
  3. Arc ve Mutex ile Paylaşma
  4. Birleştirme ve Sonuçları Toplama
← Learn Rust Coding Sayfasına Dön