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

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.

主站蜘蛛池模板: 冀州市| 松滋市| 新平| 威海市| 乐业县| 霍邱县| 高雄市| 广水市| 沙湾县| 璧山县| 凉城县| 梧州市| 大安市| 固阳县| 吴旗县| 岱山县| 莲花县| 威信县| 枞阳县| 济南市| 吴川市| 黔西县| 贡山| 万荣县| 寿宁县| 北安市| 奉化市| 乳山市| 宜丰县| 三门峡市| 仁化县| 安化县| 自贡市| 美姑县| 宜章县| 蓬莱市| 大渡口区| 永胜县| 桂林市| 松阳县| 兴安盟|