1 线程基础

1.1 定义与概念

01.线程定义
    a.概念
        线程是操作系统调度的最小单位,一个进程可以包含多个线程。
    b.Rust线程特点
        所有权系统保证线程安全。
        编译时防止数据竞争。
        轻量级线程创建。

1.2 创建线程:thread::spawn

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();
        }
        ---

1.5 线程命名:Builder

01.Builder模式
    a.功能说明
        使用Builder为线程设置名称和栈大小。
    b.代码示例
        ---
        use std::thread;

        fn main() {
            let builder = thread::Builder::new()
                .name("worker".to_string())
                .stack_size(4 * 1024 * 1024);

            let handle = builder.spawn(|| {
                println!("Thread name: {:?}", thread::current().name());
            }).unwrap();

            handle.join().unwrap();
        }
        ---

1.6 线程睡眠:sleep

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);
        }
        ---

2.2 发送者与接收者:Sender、Receiver

01.Sender
    a.功能说明
        发送者用于发送消息。
    b.代码示例
        ---
        use std::sync::mpsc;

        fn main() {
            let (tx, rx) = mpsc::channel();
            tx.send(42).unwrap();
            println!("{}", rx.recv().unwrap());
        }
        ---

02.Receiver
    a.功能说明
        接收者用于接收消息。
    b.recv方法
        阻塞等待消息。
    c.try_recv方法
        非阻塞尝试接收。

2.3 多生产者单消费者:mpsc

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);
            }
        }
        ---

2.4 同步通道与异步通道

01.异步通道
    a.定义
        mpsc::channel()创建异步通道,缓冲区无限大。
    b.特点
        发送不会阻塞。

02.同步通道
    a.定义
        mpsc::sync_channel(n)创建同步通道,缓冲区大小为n。
    b.代码示例
        ---
        use std::sync::mpsc;
        use std::thread;

        fn main() {
            let (tx, rx) = mpsc::sync_channel(1);

            thread::spawn(move || {
                tx.send(1).unwrap();
                println!("Sent 1");
                tx.send(2).unwrap();
                println!("Sent 2");
            });

            thread::sleep(std::time::Duration::from_secs(1));
            println!("Received: {}", rx.recv().unwrap());
            println!("Received: {}", rx.recv().unwrap());
        }
        ---

2.5 crossbeam-channel

01.crossbeam特点
    a.功能更强
        支持多生产者多消费者。
    b.性能更好
        比标准库channel性能更高。
    c.代码示例
        ---
        use crossbeam::channel;

        fn main() {
            let (s, r) = channel::unbounded();
            s.send(42).unwrap();
            println!("{}", r.recv().unwrap());
        }
        ---

2.6 flume库

01.flume特点
    a.高性能
        专为高性能设计的channel库。
    b.代码示例
        ---
        use flume;

        fn main() {
            let (tx, rx) = flume::unbounded();
            tx.send(42).unwrap();
            println!("{}", rx.recv().unwrap());
        }
        ---

2.7 通信模式对比

01.标准库mpsc
    a.优点
        标准库自带,无需额外依赖。
    b.缺点
        只支持单消费者。

02.crossbeam-channel
    a.优点
        功能强大,支持多消费者。
    b.适用场景
        复杂的并发通信场景。

03.flume
    a.优点
        性能最高。
    b.适用场景
        高性能要求的场景。

3 共享状态并发

3.1 Arc:原子引用计数

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();
            }
        }
        ---

3.4 内存顺序与可见性

01.内存可见性
    a.概念
        一个线程对共享数据的修改,其他线程何时能看到。
    b.Rust保证
        通过锁和原子操作保证内存可见性。

3.5 Send与Sync trait

01.Send trait
    a.定义
        实现Send的类型可以在线程间转移所有权。
    b.示例
        大多数类型都实现了Send。

02.Sync trait
    a.定义
        实现Sync的类型可以在线程间共享引用。
    b.示例
        Arc<T>要求T实现Send + Sync。

3.6 线程安全类型

01.线程安全类型
    a.Arc
        原子引用计数。
    b.Mutex
        互斥锁。
    c.RwLock
        读写锁。
    d.Atomic类型
        原子类型。

3.7 数据竞争预防

01.Rust防止数据竞争
    a.所有权系统
        编译时检查数据访问。
    b.类型系统
        Send和Sync trait保证线程安全。
    c.借用检查器
        防止同时存在可变和不可变引用。

4 线程池

4.1 线程池概念

01.线程池定义
    a.概念
        预先创建一组线程,重复使用这些线程执行任务。
    b.优势
        避免频繁创建销毁线程的开销。
        控制并发数量。

4.2 rayon库

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();
            }
        }
        ---

4.5 任务调度

01.任务调度策略
    a.FIFO
        先进先出。
    b.优先级队列
        根据优先级调度。
    c.工作窃取
        空闲线程从其他线程窃取任务。

4.6 工作窃取算法

01.工作窃取
    a.概念
        空闲线程从其他线程的任务队列中窃取任务。
    b.优势
        负载均衡,提高CPU利用率。
    c.rayon实现
        rayon内部使用工作窃取算法。

4.7 性能优化

01.线程数量
    a.建议
        通常设置为CPU核心数。
    b.代码示例
        ---
        use std::thread;

        fn main() {
            let num_cpus = thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1);
            println!("CPU cores: {}", num_cpus);
        }
        ---

02.任务粒度
    a.建议
        任务不宜过小,避免调度开销。
        任务不宜过大,影响负载均衡。

5 高级特性

5.1 线程局部存储:thread_local

01.thread_local宏
    a.定义
        每个线程拥有独立的变量副本。
    b.代码示例
        ---
        use std::cell::RefCell;
        use std::thread;

        thread_local! {
            static COUNTER: RefCell<u32> = RefCell::new(0);
        }

        fn main() {
            COUNTER.with(|c| {
                *c.borrow_mut() = 1;
            });

            thread::spawn(|| {
                COUNTER.with(|c| {
                    *c.borrow_mut() = 2;
                    println!("Thread: {}", *c.borrow());
                });
            }).join().unwrap();

            COUNTER.with(|c| {
                println!("Main: {}", *c.borrow());
            });
        }
        ---

5.2 作用域线程:scope

01.scope函数
    a.功能说明
        创建作用域线程,可以借用局部变量。
    b.代码示例
        ---
        use std::thread;

        fn main() {
            let mut data = vec![1, 2, 3];

            thread::scope(|s| {
                s.spawn(|| {
                    println!("{:?}", data);
                });

                s.spawn(|| {
                    data.push(4);
                });
            });

            println!("{:?}", data);
        }
        ---

5.3 panic处理

01.线程panic
    a.行为
        线程panic不会影响其他线程。
    b.代码示例
        ---
        use std::thread;

        fn main() {
            let handle = thread::spawn(|| {
                panic!("Thread panicked");
            });

            match handle.join() {
                Ok(_) => println!("Thread finished"),
                Err(e) => println!("Thread panicked: {:?}", e),
            }

            println!("Main continues");
        }
        ---

5.4 线程优先级

01.线程优先级
    a.说明
        Rust标准库不直接支持设置线程优先级。
    b.平台相关
        需要使用平台特定的API。

5.5 CPU亲和性

01.CPU亲和性
    a.概念
        将线程绑定到特定CPU核心。
    b.使用场景
        高性能计算、实时系统。
    c.实现
        需要使用第三方库如core_affinity。

5.6 并行迭代器

01.rayon并行迭代器
    a.功能说明
        将串行迭代器转换为并行迭代器。
    b.代码示例
        ---
        use rayon::prelude::*;

        fn main() {
            let sum: i32 = (1..1000)
                .into_par_iter()
                .map(|x| x * 2)
                .sum();
            println!("Sum: {}", sum);
        }
        ---

5.7 并发模式与最佳实践

01.最佳实践
    a.优先使用消息传递
        避免共享状态的复杂性。
    b.最小化锁的持有时间
        减少锁竞争。
    c.使用Arc而非Rc
        Arc是线程安全的。
    d.避免死锁
        统一锁的获取顺序。

02.并发模式
    a.生产者-消费者
        使用channel实现。
    b.工作池
        使用线程池处理任务。
    c.管道
        多个阶段串行处理数据。