首页 > 其他分享 >Rust Thread Adventure

Rust Thread Adventure

时间:2024-04-04 13:55:54浏览次数:24  
标签:use Thread thread let Adventure threads data Rust

Hello everyone and welcome to the wonderful world of Rust Multithreading! Today, we're going to explore this exciting area together. Are you ready? Buckle up and let's go!

In Rust, threads are like the superheroes of your program. They can perform multiple tasks at the same time, just like Superman can save multiple cities at once. By using threads, we can make our programs more powerful and harness the huge potential of multi-core processors.

Creating a thread is as easy as magic. We just need to use the thread::spawn function and "whoosh!" A new thread is born. It's like an excited little baby, ready to start its adventure.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("I'm a newborn thread baby!");
    });

    handle.join().unwrap();
}

But wait! In the world of Rust, thread safety and ownership are like our seat belts. Rust's ownership system acts like a strict traffic cop, ensuring threads don't get into "accidents" like data races. So, when we spawn threads, we need to follow Rust's traffic rules and "move" the necessary data into the thread, just like giving a safe toy to a little baby.

use std::thread;

fn main() {
    let data = vec![1, 2, 3, 4, 5];

    let handle = thread::spawn(move || {
        println!("Look at my safe toy: {:?}", data);
    });

    handle.join().unwrap();
}

In this case, we use the move keyword to transfer ownership of the data vector into the thread. This ensures that the thread has exclusive access to the data, preventing data races.

Sharing Data Between Threads:

Sometimes, we need to share data between threads. Rust provides several synchronization primitives to facilitate safe data sharing, such as mutexes (Mutex) and read-write locks (RwLock).

Here's an example that demonstrates using a mutex to share data between threads:

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let secret_box = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let secret_box = Arc::clone(&secret_box);
        let handle = thread::spawn(move || {
            let mut num = secret_box.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("The secret in the secret box is: {}", *secret_box.lock().unwrap());
}

In this example, we use an Arc (Atomically Reference Counted) to allow multiple threads to share ownership of a Mutex. The Mutex ensures that only one thread can access the shared data at a time, preventing data races.

Scoped Threads:

Rust also provides scoped threads through the thread::scope function. Scoped threads allow you to spawn threads that borrow data from the parent thread, eliminating the need for explicit synchronization.


use std::thread;

fn main() {
    let data = vec![1, 2, 3];

    thread::scope(|s| {
        s.spawn(|| {
            println!("Hey, I can directly use the parent thread's data: {:?}", data);
        });
    });
}

In a nutshell, multithreading in Rust is like an exciting adventure. With the powerful tools and safety guarantees provided by Rust, we can supercharge our programs and harness the immense potential of multi-core processors.

标签:use,Thread,thread,let,Adventure,threads,data,Rust
From: https://www.cnblogs.com/stephenTHF/p/18114134

相关文章

  • Rust中声明变量的方式
    letmutguess=String::new();在Rust中,一般使用let声明变量,比如letapples=5;这行代码声明了一个名为apples的变量,并绑定其变量值为5,在Rust中变量默认是不可变的immutable。意味着一旦给变量赋值后,其值不会发生改变。需要声明可变的变量,需要在变量名之前加mut,比如letappl......
  • Rust vs C++:2024,谁更懂错误处理?
    讲动人的故事,写懂人的代码「席双嘉,听说你的C++项目又因为忘了检查返回值导致内存泄漏,又加班了?」周五中午,在国内某科技巨头熙熙攘攘的员工餐厅,贾克强半开玩笑地戳了戳坐在隔壁的席双嘉,眼神中满是戏谑。贾克强,一个热衷于Rust的程序员,总是乐于挑战和探索新技术的边界。而席......
  • 深入理解ThreadLocal原理
    目录1-什么是ThreadLocal?2-ThreadLocal的作用?ThreadLocal实现线程间资源隔离ThreadLocal实现线程内资源共享3-ThreadLocal原理3-1ThreadLocalMap3-2ThreadLocalMap的扩容......
  • Mac 安装rustscan
    1. 安装docker.https://desktop.docker.com/mac/main/amd64/Docker.dmg?_gl=1*14rgpxs*_ga*MTI2ODM5NDc4Mi4xNzEyMDYyNzAw*_ga_XJWPQMJYHQ*MTcxMjA2MjcwMC4xLjEuMTcxMjA2MjcyOC4zMi4wLjA.2.打开docker应用程序open/Applications/Docker.app3.  4. 配置命令别名:......
  • ThreadLocal源码解析
    方法三个主要方法:getsetremove讲三个方法前,现需要知道Thread,ThreadLocal,ThreadLocalMap三个之间的关系,首先ThreadLocalMap虽然是ThreadLocal中定义的静态内部类,但实际的ThreadLocalMap实例是作为Thread对象的一个字段存在的。这样设计的目的是允许每个线程存储自己......
  • Thread join()的使用场景和原理
    1、使用场景一般情况下,主线程创建并启动子线程,如果子线程中执行大量耗时运算,主线程可能早于子线程结束。如果主线程需要知道子线程的执行结果时,就需要等待子线程执行结束。主线程可以sleep(xx),但这样的xx时间不好确定,因为子线程的执行时间不确定,join()方法比较合适这个场景。......
  • rust语法super、self和Self
    当调用模块的函数时,需要指定完整的路径。1)use关键字包括范围内的所有模块。因此,可以直接调用函数,而不必在调用函数时包含模块。Rust中的use关键字缩短了调用函数的长度,使函数的模块在范围内。2)使用*运算符*运算符用于将所有项目放入范围,这也称为glob运算符。如果使用glob运算......
  • Thread 类使用及常用操作
    Thread类是JVM用来管理线程的一个类,换句话说,每个线程都有一个唯一的Thread对象与之关联。每个执行流,也需要有一个对象来描述,类似下图所示,而Thread类的对象就是用来描述一个线程执行流的,JVM会将这些Thread对象组织起来,用于线程调度,线程管理。1Thread的常见构造方......
  • Threadx rtos 移植指南(stm32f1)
    Threadx系统移植非常简单,下面记录gnu工具链移植步骤库文件目录.├──cmake#CMakelistfilesforbuildingtheproject├──common#CoreThreadXfiles├──common_modules#CoreThreadXmodul......
  • Rust 实现日志记录功能
    目录log日志库标准简单示例使用方法库的开发者应用开发者日志库开发者使用log4rs添加依赖配置文件运行项目参考文章log日志库标准log是Rust的日志门面库,由官方积极维护可以放心使用。它是Rust的日志门面,相应的日志API已成为事实上的标准被其它日志框架所使用,有了日志门......