Closed fan-tastic-z closed 1 month ago
是不是应该使用Arc 包一下
fn atomic_cell_multiple_threads_example() {
let count = Arc::new(AtomicCell::new(0i32));
let mut handles = vec![];
for _ in 0..10 {
let count_clone = count.clone();
let handle = thread::spawn(move || {
let c = count_clone.fetch_add(1);
println!("Incremented count to {}", c + 1);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final count is {}", count.load())
}
对,有问题
对,有问题
有考虑更新pdf 么?因为看后面pdf 中还是存在错误代码
对,有问题
有考虑更新pdf 么?因为看后面pdf 中还是存在错误代码
会,欢迎指出后续的错误
在 pdf 中 11.2.2 ArrayQueue 的代码也是存在问题, 需要使用 Arc
use std::{sync::Arc, thread};
use crossbeam::queue::ArrayQueue;
fn main() {
let queue = Arc::new(ArrayQueue::new(100));
for i in 0..10 {
let queue_clone = queue.clone();
thread::spawn(move || {
queue_clone.push(i).unwrap();
});
}
for _ in 0..10 {
let queue = queue.clone();
thread::spawn(move || {
while let Some(item) = queue.pop() {
println!("Consumed {}", item);
}
});
}
}
SegQueue 示例代码也是同样的问题
use std::{sync::Arc, thread};
use crossbeam::queue::SegQueue;
fn main() {
let seg_queue = Arc::new(SegQueue::new());
let seg_queue_clone = seg_queue.clone();
let producer = thread::spawn(move || {
for i in 0..5 {
seg_queue_clone.push(i);
println!("Producer: pushed {}", i);
}
});
let seg_queue_clone2 = seg_queue.clone();
let consumer = thread::spawn(move || {
for _ in 0..5 {
let i = seg_queue_clone2.pop().unwrap();
println!("Consumer: popped {}", i);
}
});
producer.join().unwrap();
consumer.join().unwrap();
}
AtomicCell没有实现 Clone trait, 这里代码是不是有问题?