#thread #worker-thread #schedule #work

雇主

启动工作线程并在之后检查它们

1 个不稳定版本

0.1.0 2020年5月2日

并发 中排名第 936

MIT 许可证

20KB
390

描述

此 crate 提供了一个接口,用于启动工作线程并检查它们的工作是否完成并生成了结果。

何时使用此工具?

此 crate 设计用于需要执行一些昂贵任务的应用程序,但主线程在没有该任务结果的情况下仍能正常运行。此类问题的最常见领域是资源加载。此 crate 允许您开始加载资源,然后在加载完成后进行渲染/播放/使用。

示例

use std::{thread, time::Duration};
use employe::*;

fn main () {
    // Create a new `Employer`
    // We give it a work function that will be run on each input
    let employer = Employer::new(|i: i32| {
        // Sleep to simulate a more complex computation
        thread::sleep(Duration::from_millis(100));
        2 * i + 1
    });

    // Start some jobs
    employer.start(1);
    employer.start(2);
    employer.start(3);

    // Each job should take about 100 ms, so if we check them
    // immediately, they should still all be in progress
    assert!(employer.get(&1).is_in_progress());
    assert!(employer.get(&2).is_in_progress());
    assert!(employer.get(&3).is_in_progress());

    // Sleep the main thread to let the jobs finish
    thread::sleep(Duration::from_millis(200));

    // Check the results
    assert_eq!(employer.get(&1).finished().unwrap(), 3);
    assert_eq!(employer.get(&2).finished().unwrap(), 5);
    assert_eq!(employer.get(&3).finished().unwrap(), 7);
}

依赖项

~290KB