#thread #pass #borrow #thread-safe #spawn #join

nightly borrowed-thread

线程安全地传递借用给 thread::spawn

4 个版本

0.1.3 2018 年 11 月 16 日
0.1.2 2018 年 11 月 16 日
0.1.1 2018 年 11 月 16 日
0.1.0 2018 年 11 月 16 日

#1087并发

MIT 许可证

6KB
138

borrowed-thread

线程安全地传递借用给 thread::spawn

需要 nightly rust!

基准测试

测试 bench::bench_borrowed_thread ... 基准:18,902 ns/iter (+/- 690)

测试 bench::bench_std_thread ... 基准:18,859 ns/iter (+/- 684)

示例

使用 &mut

use borrowed_thread;

let mut owned = "ABC".to_owned();

let borrowed_handle = borrowed_thread::spawn(|| {
    owned.push('D');
    0
});

let ret = borrowed_handle.join().expect("join err");

assert_eq!(0, ret);
assert_eq!("ABCD", owned);

使用 &

use borrowed_thread;

let owned = "ABC".to_owned();

let borrowed_handle = borrowed_thread::spawn(|| {
    assert_eq!("ABC", owned);
    0
});

let ret = borrowed_handle.join().expect("join err");

assert_eq!(0, ret);

当没有 join 时释放会 panic

let mut owned = "ABC".to_owned();

let borrowed_handle = borrowed_thread::spawn(|| {
    owned.push('D');
    0
});

// this will cause panic!
drop(borrowed_handle);

assert_eq!("ABCD", owned);

无运行时依赖