R

Concorrência

Rust Syntax Guide

Escrever código concorrente seguro e eficiente em Rust

Concorrência

Escrever código concorrente seguro e eficiente em Rust

Rust concorrência (rust)
        
          use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
use std::sync::mpsc;

// Basic thread creation
fn basic_threads() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    handle.join().unwrap();

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

// Moving data into threads
fn move_data() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}

// Message passing with channels
fn message_passing() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
        // println!("val is {}", val); // Error: val was moved
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

// Multiple producers
fn multiple_producers() {
    let (tx, rx) = mpsc::channel();
    let tx2 = tx.clone();

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });

    thread::spawn(move || {
        let vals = vec![
            String::from("more"),
            String::from("messages"),
            String::from("for"),
            String::from("you"),
        ];

        for val in vals {
            tx2.send(val).unwrap();
            thread::sleep(Duration::from_millis(100));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}

// Shared state with Mutex
fn shared_state() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

// Read-write lock
use std::sync::RwLock;

fn read_write_lock() {
    let lock = Arc::new(RwLock::new(5));
    let lock_clone = Arc::clone(&lock);

    let handle = thread::spawn(move || {
        let read_guard = lock_clone.read().unwrap();
        println!("Read value: {}", *read_guard);
        // Multiple readers can hold the lock simultaneously
    });

    {
        let write_guard = lock.write().unwrap();
        *write_guard += 1;
        println!("Modified value to: {}", *write_guard);
    } // Write lock is released here

    handle.join().unwrap();
}

// Async programming (experimental in stable Rust)
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// Simple async function
async fn hello_world() {
    println!("Hello, world!");
}

// Async function with await
async fn async_example() -> String {
    hello_world().await; // Wait for hello_world to complete
    String::from("Done!")
}

fn main() {
    // Basic threads
    println!("=== Basic Threads ===");
    basic_threads();

    // Move data
    println!("\n=== Move Data ===");
    move_data();

    // Message passing
    println!("\n=== Message Passing ===");
    message_passing();

    // Multiple producers
    println!("\n=== Multiple Producers ===");
    multiple_producers();

    // Shared state
    println!("\n=== Shared State ===");
    shared_state();

    // Read-write lock
    println!("\n=== Read-Write Lock ===");
    read_write_lock();

    // Note: Async example requires async runtime like tokio
    // println!("\n=== Async Example ===");
    // let future = async_example();
    // This would need an async runtime to execute
}
        
      

Explanation

Rust fornece primitivas de concorrência poderosas como threads e canais (para passagem de mensagens) que são projetadas para serem seguras e prevenir bugs comuns de concorrência em tempo de compilação, graças ao seu sistema de propriedade e empréstimo.

Common Use Cases

  • Paralelizar computações
  • Construir interfaces de usuário responsivas
  • Desenvolver servidores de alto desempenho
  • Lidar com tarefas em segundo plano

Related Rust Syntax

Master Concorrência in Rust

Understanding Concorrência is fundamental to writing clean and efficient Rust code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Concorrência effectively in your Rust projects.

Key Takeaways

  • Paralelizar computações
  • Construir interfaces de usuário responsivas
  • Desenvolver servidores de alto desempenho