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

Concurrency and mutability

Rust's approach to managing memory is a powerful concept. In fact, it is powerful enough to also facilitate concurrency and parallel execution. However, first things first: how do threads work in the Rust standard library?

Concurrency and parallelism are two different modes of execution. While concurrency means that parts of a program run independently of each other, parallelism refers to these parts executing at the same time. For simplicity, we will refer to both concepts as concurrency.

Due to its low-level nature, Rust provides an API to the operating system's threading capabilities (for example, POSIX on Linux/Unix systems). If no variables are passed into the scope, their usage is very straightforward:

use std::thread; 

fn threading() {
// The to pipes (||) is the space where parameters go,
// akin to a function signature's parameters, without
// the need to always declare types explicitly.
// This way, variables can move from the outer into the inner scope
let handle = thread::spawn(|| {
println!("Hello from a thread");
});
handle.join().unwrap();
}

However, when passing data back and forth, more work has to be done to hold up Rust's safety guarantees, especially when mutability comes into play. Before getting into that, it is important to recap immutability.

主站蜘蛛池模板: 崇文区| 子长县| 汤阴县| 鸡西市| 莱州市| 乳源| 乾安县| 龙泉市| 柏乡县| 湖州市| 涟源市| 句容市| 涿州市| 习水县| 桃园市| 沂水县| 色达县| 香格里拉县| 宝兴县| 西乌珠穆沁旗| 阿鲁科尔沁旗| 云浮市| 长武县| 玛纳斯县| 建湖县| 双鸭山市| 临武县| 巴塘县| 布拖县| 固始县| 泰宁县| 兴城市| 威远县| 西城区| 兴和县| 乌兰县| 荆门市| 马鞍山市| 绥江县| 伊金霍洛旗| 玉门市|