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

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.

主站蜘蛛池模板: 广平县| 涪陵区| 梨树县| 东方市| 宁安市| 瓮安县| 隆安县| 溧阳市| 双桥区| 克东县| 诏安县| 卢氏县| 亳州市| 准格尔旗| 叙永县| 镇江市| 贵港市| 天等县| 东乡县| 宁波市| 社旗县| 德格县| 闽清县| 西青区| 遵义县| 北京市| 裕民县| 那曲县| 额济纳旗| 泽州县| 武宣县| 肇源县| 五莲县| 铁岭市| 巫溪县| 哈密市| 始兴县| 巴彦淖尔市| 如皋市| 屏东县| 芷江|