Rust 中的并发模型和所有权系统

原文链接:mp.weixin.qq.com/s/fDcClchcJ...

Rust 是一种现代编程语言,专为性能敏感和系统级开发设计。 Rust 的关键特性之一是其所有权系统,该系统赋予开发者内存安全的同时不影响性能。 此外,Rust 支持多种并发模型,使得用 Rust 策划并发爬虫或者并发 web server 成为可能。本文将深入探讨 Rust 的这些特性。

并发模型

在 Rust 里,可以通过两者方式来进行并发编程:线程模型和消息传递模型。

  1. 线程模型:Rust 的标准库提供了一套包含线程创建、锁和其他并发原语的完整工具集合。并发包 std::thread 可以轻易地创建线程以运行一个闭包,并获取其返回值。
rust 复制代码
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}
  1. 消息传递模型:Rust 通过 std::sync::mpsc 使用了一种多生产者单消费者 (MPSC) 的消息队列模型。这种模型允许多个线程共享数据,而无需显式的同步操作。
rust 复制代码
use std::thread;
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();  

    thread::spawn(move || {
        let val = String::from("Hello");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

所有权系统

在 Rust 中,所有权系统用于管理内存。这是通过一些规则实现的,编译器在编译时就会检查这些规则。

  1. 变量取值默认是移动语义,也就是深拷贝。这一点在处理动态内存数据结构时表现的尤为重要。例如:
rust 复制代码
let s1 = String::from("hello");
let s2 = s1;
println!("{}, world!", s1); 

上述代码会在编译时报错,因为 s1let s2 = s1; 语句后就失去了所有权,不能再被使用。

  1. 在函数中,所有权也会被转移。
rust 复制代码
fn main() {
    let s = String::from("hello");
    takes_ownership(s);
    //`s` 的所有权已经被 `takes_ownership` 所获得,这里再使用就会编译错误
    //println!("In main: {}", s);
}

fn takes_ownership(some_string: String) {
    println!("{}", some_string);
} 

通过所有权和这两种并发模型,Rust 成为了一种有内存安全保证,性能强大的并发编程语言。并发编程并优秀的类型系统使 Rust 成为系统编程和开发高性能应用的绝佳选择。

相关推荐
小马爱打代码9 小时前
SpringBoot:封装 starter
java·spring boot·后端
STARSpace888810 小时前
SpringBoot 整合个推推送
java·spring boot·后端·消息推送·个推
Marktowin10 小时前
玩转 ZooKeeper
后端
蓝眸少年CY11 小时前
(第十二篇)spring cloud之Stream消息驱动
后端·spring·spring cloud
码界奇点11 小时前
基于SpringBoot+Vue的前后端分离外卖点单系统设计与实现
vue.js·spring boot·后端·spring·毕业设计·源代码管理
lindd91191112 小时前
4G模块应用,内网穿透,前端网页的制作第七讲(智能头盔数据上传至网页端)
前端·后端·零基础·rt-thread·实时操作系统·项目复刻
Loo国昌12 小时前
【LangChain1.0】第八阶段:文档处理工程(LangChain篇)
人工智能·后端·算法·语言模型·架构·langchain
vx_bisheyuange12 小时前
基于SpringBoot的海鲜市场系统
java·spring boot·后端·毕业设计
李慕婉学姐13 小时前
【开题答辩过程】以《基于Spring Boot和大数据的医院挂号系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
大数据·spring boot·后端
源代码•宸14 小时前
Leetcode—3. 无重复字符的最长子串【中等】
经验分享·后端·算法·leetcode·面试·golang·string