在Linux環境下,使用Rust進行并發編程可以通過以下幾種方式實現:
Rust的標準庫提供了std::thread
模塊,可以用來創建和管理線程。
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from a thread!");
});
handle.join().unwrap();
}
Rust的std::sync::mpsc
模塊提供了多生產者單消費者(MPSC)通道,可以用來在線程之間傳遞消息。
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Arc
和Mutex
Arc
(原子引用計數)和Mutex
(互斥鎖)可以用來在多個線程之間共享和保護數據。
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
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());
}
async
/await
Rust的async
/await
語法可以用來編寫異步代碼,這對于I/O密集型任務非常有用。
use tokio::net::TcpListener;
use tokio::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let bytes_read = match socket.read(&mut buf).await {
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
eprintln!("Failed to read from socket: {:?}", e);
return;
}
};
// Write the data back
if let Err(e) = socket.write_all(&buf[0..bytes_read]).await {
eprintln!("Failed to write to socket: {:?}", e);
return;
}
}
});
}
}
還有一些第三方庫可以幫助你更方便地進行并發編程,例如:
use rayon::prelude::*;
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.par_iter().sum();
println!("Sum: {}", sum);
}
use tokio::net::TcpListener;
use tokio::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let bytes_read = match socket.read(&mut buf).await {
Ok(n) if n == 0 => return,
Ok(n) => n,
Err(e) => {
eprintln!("Failed to read from socket: {:?}", e);
return;
}
};
// Write the data back
if let Err(e) = socket.write_all(&buf[0..bytes_read]).await {
eprintln!("Failed to write to socket: {:?}", e);
return;
}
}
});
}
}
通過這些方法,你可以在Linux環境下使用Rust進行高效的并發編程。