【发布时间】:2020-07-07 21:06:26
【问题描述】:
我未能通过借用检查器获取此代码:
use std::sync::Arc;
use std::thread::{sleep, spawn};
use std::time::Duration;
#[derive(Debug, Clone)]
struct State {
count: u64,
not_copyable: Vec<u8>,
}
fn bar(thread_num: u8, arc_state: Arc<State>) {
let state = arc_state.clone();
loop {
sleep(Duration::from_millis(1000));
println!("thread_num: {}, state.count: {}", thread_num, state.count);
}
}
fn main() -> std::io::Result<()> {
let mut state = State {
count: 0,
not_copyable: vec![],
};
let arc_state = Arc::new(state);
for i in 0..2 {
spawn(move || {
bar(i, arc_state.clone());
});
}
loop {
sleep(Duration::from_millis(300));
state.count += 1;
}
}
我可能尝试了错误的事情。
我想要一个可以更新state 的(主)线程和多个可以读取state 的线程。
我应该如何在 Rust 中做到这一点?
我已阅读 the Rust book on shared state,但它使用的互斥锁对于单个写入器/多个读取器的情况来说似乎过于复杂。
在 C 语言中,我会通过大量的 _Atomic 来实现这一点。
【问题讨论】:
标签: multithreading rust borrow-checker