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

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.

主站蜘蛛池模板: 福清市| 黄浦区| 建阳市| 阿拉善盟| 元江| 大名县| 郯城县| 禹州市| 天峻县| 乐亭县| 谷城县| 中江县| 南华县| 镇远县| 大埔区| 抚宁县| 湖州市| 琼海市| 河源市| 凭祥市| 吉安市| 屯留县| 竹山县| 随州市| 东乌珠穆沁旗| 开封县| 梁山县| 长兴县| 靖远县| 宁南县| 开平市| 卢龙县| 金乡县| 新竹市| 宜黄县| 甘肃省| 北票市| 河间市| 大丰市| 冷水江市| 靖州|