官术网_书友最值得收藏!

Sharing data

Other than sending data into threads one way, many programs operate on a shared state where multiple execution streams have to access and change one or more shared variables. Typically, this warrants a mutex (short for mutual exclusion), so that any time something is accessed within this locked mutex, it is guaranteed to be a single thread.

This is an old concept and implemented in the Rust standard library. How does that facilitate accessing a variable? Wrapping a variable into a Mutex type will provide for the locking mechanism, thereby making it accessible from multiple concurrent writers. However, they don't have ownership of that memory area yet.

In order to provide that ownership across threads—similar to what Rc does within a single thread—Rust provides the concept of an Arc, an atomic reference counter. Using this Mutex on top, it's the thread-safe equivalent of an Rc wrapping a RefCell, a reference counter that wraps a mutable container. To provide an example, this works nicely:

use std::thread;
use std::sync::{Mutex, Arc};

fn shared_state() {
let v = Arc::new(Mutex::new(vec![]));
let handles = (0..10).map(|i| {
let numbers = Arc::clone(&v);
thread::spawn(move || {
let mut vector = numbers
.lock()
.unwrap();
(*vector).push(i);
})
});

for handle in handles {
handle.join().unwrap();
}
println!("{:?}", *v.lock().unwrap());
}

When running this example, the output is this:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

While the preferred way of doing concurrent programming is still to use immutable variables as often as possible, safe Rust provides the tools for working with shared data without side effects.

主站蜘蛛池模板: 达州市| 兴文县| 民勤县| 安庆市| 山西省| 襄樊市| 牟定县| 衡山县| 万安县| 鄂尔多斯市| 杭锦后旗| 闻喜县| 噶尔县| 辽阳县| 景泰县| 永川市| 铅山县| 视频| 湘乡市| 翁源县| 谢通门县| 广德县| 康马县| 隆尧县| 嘉祥县| 易门县| 廊坊市| 阿鲁科尔沁旗| 酒泉市| 高邑县| 平遥县| 喀喇沁旗| 宜城市| 揭西县| 扎兰屯市| 富川| 泰安市| 锦州市| 东丽区| 汽车| 阿克苏市|