#thread-pool #thread #executor #task-pool

executor-service

类似于 Java ExecutorService 的快速高效的线程池

2 个版本

0.2.2 2023 年 3 月 14 日
0.2.1 2023 年 3 月 13 日
0.1.3 2023 年 3 月 13 日

328并发 中排名

每月 32 次下载

自定义许可协议

25KB
391

executor-service

cargo_build_workflow

Cargo Publish

为 Rust 实现的类似 Java ExecutorService 风格的线程池

创建线程池

创建固定大小的线程池

在许多情况下,您可能希望保持固定大小的线程池以并行处理传入的任务。以下是一个示例代码来实现这一点

use executor_service::Executors;
///...
fn main() {
  let mut executor_service = Executors::new_fixed_thread_pool(10).expect("Failed to create the thread pool");
  //...
}

创建缓存线程池

如果您不希望处理大小并且需要更多线程(例如,线程正在执行长时间的工作,您不想等待),则可以使用缓存线程池。以下是一个示例代码来实现这一点

use executor_service::Executors;
///...
fn main() {
  let mut executor_service = Executors::new_cached_thread_pool(Some(5)).expect("Failed to create the thread pool");
  //...
}

Some(5) 是一个可选参数,为池提供初始大小。可以提供最多 150 个线程。如果将其设置为 None,则池将具有 10 的初始大小。

执行任务而不等待结果

如果您想提交任务而不关心结果,可以使用以下 'ExecutorService::execute' 方法

use executor_service::Executors;
use std::thread::sleep;
use core::time::Duration;
use std::thread;

fn main() {
  let mut executor_service = Executors::new_fixed_thread_pool(2).expect("Failed to create the thread pool");

  let some_param = "Mr White";
  let res = executor_service.execute(move || {
    sleep(Duration::from_secs(1));
    println!("Hello {:} from thread {:}", some_param, thread::current().name().unwrap());
  }).expect("Failed to execute function");

  sleep(Duration::from_secs(3));
}

执行任务并等待结果

以下是一个示例,如果您想在池上运行任务并同步等待结果

use executor_service::Executors;
use std::thread::sleep;
use core::time::Duration;
fn main() {
  let mut executor_service = Executors::new_cached_thread_pool(None)
    .expect("Failed to create the thread pool");
  let some_param = "Mr White";
  let res = executor_service.submit_sync(move || {
    println!("Long computation started");
    sleep(Duration::from_secs(5));
    println!("Hello {:}", some_param);
    println!("Long computation finished");
    2
  }).expect("Failed to submit function");
  println!("Result: {:#?}", res);
  assert_eq!(res, 2);
}

执行任务并获取异步结果

以下是一个示例,如果您想在池上运行任务并获取结果的 Future

use executor_service::Executors;
use std::thread::sleep;
use core::time::Duration;

fn main() {
  let mut executor_service = Executors::new_cached_thread_pool(Some(5)).expect("Failed to create the thread pool");
  let some_param = "Mr White";
  let the_future = executor_service.submit_async(Box::new(move || {
    sleep(Duration::from_secs(3));
    println!("Hello {:}", some_param);
    println!("Long lasting computation finished");
    "Some string result".to_string()
  })).expect("Failed to submit function");
  
  //Wait a bit more to see the future work.
  println!("Main thread wait for 5 seconds");
  sleep(Duration::from_secs(5));
  let res = the_future.get().expect("Couldn't get a result");
  println!("Result is {:}", &res);
  assert_eq!(&res, "Some string result");
}

您可以将 Future 安全地发送到通道,以便在其他地方使用结果

我非常欢迎通过拉取请求进行贡献。谢谢!

依赖项

~87KB