Rust线程池库jxl-threadpool的使用:高性能、轻量级的多线程任务调度与管理

Rust线程池库jxl-threadpool的使用:高性能、轻量级的多线程任务调度与管理

jxl-threadpool是一个为其他jxl-oxide crate提供线程池抽象实现的Rust库。

安装

在项目目录中运行以下Cargo命令:

cargo add jxl-threadpool

或者在Cargo.toml中添加以下行:

jxl-threadpool = "1.0.0"

使用示例

下面是一个完整的jxl-threadpool使用示例:

use jxl_threadpool::ThreadPool;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    // 创建一个包含4个工作线程的线程池
    let pool = ThreadPool::new(4).expect("Failed to create thread pool");
    
    // 创建通道用于接收任务结果
    let (tx, rx) = mpsc::channel();
    
    // 提交10个任务到线程池
    for i in 0..10 {
        let tx = tx.clone();
        pool.execute(move || {
            // 模拟耗时任务
            thread::sleep(Duration::from_millis(500));
            
            // 发送任务结果
            tx.send(i * 2).expect("Failed to send result");
        });
    }
    
    // 关闭发送端
    drop(tx);
    
    // 收集所有任务结果
    let results: Vec<_> = rx.iter().collect();
    
    println!("All tasks completed. Results: {:?}", results);
}

完整示例代码

以下是jxl-threadpool的另一个完整使用示例,演示了更复杂的任务处理场景:

use jxl_threadpool::ThreadPool;
use std::sync::{Arc, Mutex};
use std::time::Duration;

fn main() {
    // 创建包含8个工作线程的线程池
    let pool = ThreadPool::new(8).unwrap();
    
    // 创建共享计数器
    let counter = Arc::new(Mutex::new(0));
    
    // 提交20个任务到线程池
    for i in 0..20 {
        let counter = Arc::clone(&counter);
        
        pool.execute(move || {
            // 模拟不同耗时的任务
            let sleep_time = if i % 2 == 0 {
                Duration::from_millis(300)
            } else {
                Duration::from_millis(700)
            };
            
            std::thread::sleep(sleep_time);
            
            // 安全地递增计数器
            let mut num = counter.lock().unwrap();
            *num += 1;
            
            println!("Task {} completed. Total completed: {}", i, *num);
        });
    }
    
    // 等待所有任务完成
    pool.wait();
    
    // 获取最终计数器值
    let final_count = *counter.lock().unwrap();
    println!("All tasks finished. Total tasks completed: {}", final_count);
}

功能特点

  1. 轻量级线程池实现
  2. 高性能任务调度
  3. 简单易用的API
  4. 适用于jxl-oxide生态中的其他crate

许可证

jxl-threadpool采用MIT或Apache-2.0双重许可证。


1 回复

jxl-threadpool:高性能、轻量级的Rust线程池库

介绍

jxl-threadpool是一个Rust实现的轻量级线程池库,专注于高性能任务调度与管理。它提供了简单易用的API来执行并行任务,适合需要高效利用多核CPU的场景。

主要特性

  • 轻量级实现,低开销
  • 高性能任务调度
  • 支持任务返回值获取
  • 可配置的线程数量
  • 线程安全的任务队列

完整示例代码

下面是一个综合使用jxl-threadpool各种功能的完整示例:

use jxl_threadpool::ThreadPool;
use jxl_threadpool::ThreadPoolBuilder;
use std::time::Duration;

fn main() {
    // 1. 基本线程池使用
    basic_threadpool_usage();
    
    // 2. 获取任务返回值
    future_result_example();
    
    // 3. 并行数据处理
    parallel_data_processing();
    
    // 4. 高级配置示例
    advanced_configuration();
}

// 基本线程池使用示例
fn basic_threadpool_usage() {
    println!("=== 基本线程池使用示例 ===");
    
    // 创建包含4个工作线程的线程池
    let pool = ThreadPool::new(4).unwrap();
    
    // 提交多个任务
    for i in 0..5 {
        pool.execute(move || {
            println!("任务{}在线程{:?}中执行", i, std::thread::current().id());
            std::thread::sleep(Duration::from_millis(100));
        });
    }
    
    // 等待所有任务完成
    pool.join();
    println!("所有基本任务已完成\n");
}

// 获取任务返回值示例
fn future_result_example() {
    println!("=== 获取任务返回值示例 ===");
    
    let pool = ThreadPool::new(2).unwrap();
    
    // 提交多个返回值的任务
    let futures = (0..3).map(|i| {
        pool.execute_future(move || {
            println!("计算任务{}开始", i);
            std::thread::sleep(Duration::from_millis(200));
            i * i // 返回平方值
        })
    }).collect::<Vec<_>>();
    
    // 获取所有任务结果
    for (i, future) in futures.into_iter().enumerate() {
        let result = future.wait().unwrap();
        println!("任务{}的结果: {}", i, result);
    }
    println!("所有返回值任务已完成\n");
}

// 并行数据处理示例
fn parallel_data_processing() {
    println!("=== 并行数据处理示例 ===");
    
    let data = (0..20).collect::<Vec<_>>();
    println!("原始数据: {:?}", data);
    
    // 使用CPU核心数创建线程池
    let pool = ThreadPool::new(num_cpus::get()).unwrap();
    
    // 将数据分块处理
    let chunk_size = 5;
    let mut futures = Vec::new();
    
    for chunk in data.chunks(chunk_size) {
        let chunk = chunk.to_vec(); // 获取数据所有权
        let future = pool.execute_future(move || {
            // 模拟耗时处理
            std::thread::sleep(Duration::from_millis(100));
            chunk.into_iter().map(|x| x * x).collect::<Vec<_>>() // 计算平方
        });
        futures.push(future);
    }
    
    // 收集所有结果
    let results: Vec<i32> = futures.into_iter()
        .flat_map(|f| f.wait().unwrap())
        .collect();
    
    println!("处理后的数据: {:?}\n", results);
}

// 高级配置示例
fn advanced_configuration() {
    println!("=== 高级配置示例 ===");
    
    // 使用ThreadPoolBuilder进行高级配置
    let pool = ThreadPoolBuilder::new()
        .num_threads(3) // 设置3个线程
        .thread_name("custom-worker".into()) // 自定义线程名称
        .build()
        .unwrap();
    
    // 提交任务
    let future = pool.execute_future(|| {
        // 模拟可能失败的操作
        if rand::random() {
            Ok("操作成功")
        } else {
            Err("操作失败")
        }
    });
    
    // 处理可能失败的任务
    match future.wait() {
        Ok(result) => println!("任务成功: {}", result),
        Err(e) => println!("任务失败: {:?}", e),
    };
    
    println!("高级配置示例完成\n");
}

性能建议

  1. 根据CPU核心数设置合适的线程数量
  2. 避免在任务中执行阻塞操作(考虑使用异步版本)
  3. 大任务可以拆分为小任务提高并行度

jxl-threadpool是一个简单高效的线程池解决方案,适合大多数需要并行处理的Rust应用场景。

回到顶部