use std::thread; fn main() { struct Point<T> { pub x: T, } let mut p = Point { x: 32 }; let mut vals = Vec::new(); for _ in 0..2 { let h = thread::spawn(move || { p.x = 5; println!("{}", p.x); }); vals.push(h); } for v in vals { v.join().unwrap(); } println!("{}", p.x); // 32 } 输出结果是两个 5 和最后的 32, 也就是说线程里修改对主线程无效
playground url: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bf8936b4cc64c1f3124e926e81d9b4d6
DDDD -_-
我这里的变量 p 为啥能在多个线程间修改和使用呢? 懂的兄弟带带我, 谢谢.
同时求一个好的 rust 社区 /论坛 /讨论区
![]() | 1 reter 2022-05-18 16:15:47 +08:00 ![]() 我分析,编译器认为只有 p.x 被移动,然后 p.x 默认是 i32 类型, 自动实现了 Copy, 所以在 move 闭包下,创建了新的变量, 复制了 p.x 的值。 如果 p 里面有其它不可移动的字段,然后在 move 闭包里面 进行了操作,那么无法通过编译。 https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a93e02138c3df6841f402b0ccbb7d7be |
![]() | 3 liuhan907 2022-05-18 17:14:07 +08:00 @BBCCBB 你的 p 的具体类型 Point<i32> 字段全满足 Sync ,所以 Point<i32> 也自动满足 Sync ,因此跨线程共享是安全的。你可以尝试用 Point<String> 试试看。 |
![]() | 4 BBCCBB OP |
![]() | 6 liuhan907 2022-05-18 18:46:38 +08:00 |
8 mr0joker 2022-05-18 23:31:15 +08:00 via iPhone rust 官网不就有个交流的地方 https://users.rust-lang.org/ |
9 mr0joker 2022-05-18 23:32:36 +08:00 via iPhone 接 8 楼,个人认为那个网站是“好的” |
![]() | 10 Buges 2022-05-19 01:41:59 +08:00 via Android ![]() 这是 rust 2021 edition 的新特性 https://doc.rust-lang.org/edition-guide/rust-2021/disjoint-capture-in-closures.html move 的只有 x ,而 x 实现了 Copy 。 |
![]() | 12 reter 2022-05-19 10:54:12 +08:00 |
![]() | 13 BBCCBB OP @reter 感谢, 10 楼链接里就是原理了... 新特性,哈哈, 不是 Copy, 是 disjoint capture |