更新时间:2023-11-13 22:02:28
由于移动闭包,您得到第一个错误:
You get the first error because of the move closure:
let mut connections = Arc::new((Mutex::new(Vec::new())));
thread::spawn(move || {
let mut i = connections.lock().unwrap().len();
....
}
这实际上移动了整个Arc
,而您只想移动它的一部分"(也就是说,以引用计数递增的方式移动它,并且两个线程可以使用).
This actually moves the whole Arc
, while you only want to move "a part" of it (that is, move it in such a way that the reference count is incremented, and that both threads can use it).
为此,我们可以使用 Arc::clone
:
To do this, we can use Arc::clone
:
let mut connections = Arc::new((Mutex::new(Vec::new())));
let conn = connections.clone();
thread::spawn(move || {
let mut i = conn.lock().unwrap().len();
....
}
这样,克隆的Arc
,conn
,被移到了闭包中,而原来的Arc
,connections代码>,不是,因此仍然可用.
This way, the cloned Arc
, conn
, is moved into the closure, and the original Arc
, connections
, is not, and hence still usable.
我不确定您对第二个错误究竟做了什么,但为了简单地计算连接数,您不需要push
整个事情.
I'm not sure exactly what you are doing with your second error, but for the sake of simply counting the connections you do not need to push
the entire thing.