01.spawn函数
a.功能说明
使用thread::spawn创建新线程。
b.代码示例
---
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("Hello from thread");
});
handle.join().unwrap();
}
---
1.3 线程句柄:JoinHandle
01.JoinHandle
a.定义
spawn返回JoinHandle,用于等待线程完成。
b.代码示例
---
use std::thread;
fn main() {
let handle = thread::spawn(|| {
42
});
let result = handle.join().unwrap();
println!("Result: {}", result);
}
---
1.4 等待线程:join
01.join方法
a.功能说明
阻塞当前线程,等待子线程完成。
b.代码示例
---
use std::thread;
fn main() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Thread: {}", i);
}
});
for i in 1..3 {
println!("Main: {}", i);
}
handle.join().unwrap();
}
---
01.sleep函数
a.功能说明
让当前线程睡眠指定时间。
b.代码示例
---
use std::thread;
use std::time::Duration;
fn main() {
println!("Start");
thread::sleep(Duration::from_secs(2));
println!("End");
}
---
1.7 线程让步:yield_now
01.yield_now函数
a.功能说明
主动让出CPU时间片给其他线程。
b.代码示例
---
use std::thread;
fn main() {
let handle = thread::spawn(|| {
for i in 0..5 {
println!("Thread: {}", i);
thread::yield_now();
}
});
for i in 0..5 {
println!("Main: {}", i);
thread::yield_now();
}
handle.join().unwrap();
}
---
2 线程间通信
2.1 消息传递:Channel
01.Channel概念
a.定义
Channel是线程间通信的管道,发送者发送消息,接收者接收消息。
b.代码示例
---
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("Hello").unwrap();
});
let msg = rx.recv().unwrap();
println!("{}", msg);
}
---
01.mpsc模式
a.定义
多个发送者,一个接收者。
b.代码示例
---
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for i in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(i).unwrap();
});
}
drop(tx);
for received in rx {
println!("{}", received);
}
}
---
01.Arc概念
a.定义
Arc是原子引用计数智能指针,用于跨线程共享数据。
b.代码示例
---
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(vec![1, 2, 3]);
let mut handles = vec![];
for _ in 0..3 {
let data = Arc::clone(&data);
let handle = thread::spawn(move || {
println!("{:?}", data);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
---
3.2 Arc与Mutex组合
01.Arc<Mutex<T>>模式
a.功能说明
Arc提供共享,Mutex提供可变性。
b.代码示例
---
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());
}
---
3.3 Arc与RwLock组合
01.Arc<RwLock<T>>模式
a.功能说明
适合读多写少的场景。
b.代码示例
---
use std::sync::{Arc, RwLock};
use std::thread;
fn main() {
let data = Arc::new(RwLock::new(vec![1, 2, 3]));
let mut handles = vec![];
for i in 0..5 {
let data = Arc::clone(&data);
let handle = thread::spawn(move || {
let v = data.read().unwrap();
println!("Reader {}: {:?}", i, *v);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
---
01.rayon特点
a.数据并行
自动将任务分配到线程池。
b.代码示例
---
use rayon::prelude::*;
fn main() {
let sum: i32 = (1..100).into_par_iter().sum();
println!("Sum: {}", sum);
}
---
4.3 threadpool库
01.threadpool使用
a.功能说明
简单的线程池实现。
b.代码示例
---
use threadpool::ThreadPool;
fn main() {
let pool = ThreadPool::new(4);
for i in 0..8 {
pool.execute(move || {
println!("Task {}", i);
});
}
pool.join();
}
---
4.4 自定义线程池
01.简单线程池实现
a.功能说明
使用channel和线程实现简单线程池。
b.代码示例
---
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
type Job = Box<dyn FnOnce() + Send + 'static>;
struct ThreadPool {
workers: Vec<thread::JoinHandle<()>>,
sender: mpsc::Sender<Job>,
}
impl ThreadPool {
fn new(size: usize) -> Self {
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for _ in 0..size {
let receiver = Arc::clone(&receiver);
let handle = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv();
match job {
Ok(job) => job(),
Err(_) => break,
}
});
workers.push(handle);
}
ThreadPool { workers, sender }
}
fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
self.sender.send(Box::new(f)).unwrap();
}
}
---