"首次提交"

This commit is contained in:
2024-06-08 15:01:12 +08:00
parent 6e0f708d0a
commit 84349a2469
112 changed files with 3272 additions and 0 deletions

1
p16.fearless_conscurrency/mutex/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "mutex"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,33 @@
fn main() {
println!("Hello, world!");
mutex_learn();
}
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn mutex_learn() {
let strings = Arc::new(Mutex::new(vec![]));
let mut ths = vec![];
for i in 1..10 {
let strings = Arc::clone(&strings); //获得一个强引用
let handle = thread::spawn(move || {
for _i in 1..3 {
strings
.lock()
.unwrap()
.push(String::from(format!("thread{}: ", i)) + &(i + _i).to_string());
thread::sleep(Duration::from_micros(
(((1 as f64) / (i as f64)) * 100.0) as u64, //线程越前的睡的越久
));
}
});
ths.push(handle);
}
for th in ths {
th.join().unwrap();
}
println!("strings is {:?}", strings.lock().unwrap());
}

View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "shared_trait"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,51 @@
//定义一个Draw trait所有实现了Draw trait的类型都要具有draw方法。
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn new() -> Screen {
Screen { components: vec![] }
}
pub fn add(&mut self, comp: Box<dyn Draw>) {
self.components.push(comp)
}
pub fn run(&self) {
if self.components.len() == 0 {
println!("has no components!");
return;
}
for obj in self.components.iter() {
obj.draw();
}
}
}
pub struct Button {
width: u32,
height: u32,
text: String,
}
impl Button {
pub fn new(width: u32, height: u32, text: &str) -> Button {
Button {
width,
height,
text: String::from(text),
}
}
}
impl Draw for Button {
fn draw(&self) {
println!(
"This is a Button, draw by {}x{} : {}",
self.width, self.height, self.text
);
}
}

View File

@ -0,0 +1,32 @@
use shared_trait::*;
struct SelectBox<'a> {
width: i32,
height: u32,
option: Vec<&'a str>,
}
impl<'a> Draw for SelectBox<'a> {
fn draw(&self) {
println!(
"This is a Button, draw by {}x{} : {:?}",
self.width, self.height, self.option
);
}
}
fn main() {
println!("Hello, world!");
let mut screen = Screen::new();
let button = Button::new(30, 40, "Button text");
screen.add(Box::new(button));
screen.add(Box::new(SelectBox {
width: 100,
height: 300,
option: vec!["option1", "option2", "option3"],
}));
// screen.add(Box::new(String::from("asdad"))); //the trait bound `String: shared_trait::Draw` is not satisfied
screen.run();
}

1
p16.fearless_conscurrency/thread/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,8 @@
[package]
name = "thread"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@ -0,0 +1,98 @@
fn main() {
println!("Hello, world!");
thread_learn();
thread_learn1();
thread_learn2();
}
use std::thread;
use std::time::Duration;
fn thread_learn() {
let handle = thread::spawn(|| {
for i in 1..5 {
println!("thread {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..5 {
println!("main {}", i);
thread::sleep(Duration::from_millis(50));
}
handle.join().unwrap();
}
fn thread_learn1() {
let v = vec![1, 2, 3, 4];
//闭包是可以直接捕获上下文中的变量并使用的但是在线程里不行。因为rust无法获知线程合适结束也就
//无法保证v的有效性。如果需要在threa里使用主线程中的变量。需要使用move将其移动到子线程
//这样主线程也就不在拥有v的所有权了
/* 这种方式会编译不过。因为v不可以再子线程使用 */
// let handle = thread::spawn(|| {
// println!("thread {:?}", v);
// });
// println!("main {:?}", v);
/* 这种方式会编译不过。因为v被移动到子线程主线程已不可使用 */
let handle = thread::spawn(move || {
println!("thread {:?}", v);
});
//println!("main {:?}", v);
handle.join().unwrap();
}
use std::sync::mpsc;
fn thread_learn2() {
let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx); //再产生一个生产者
let handle = thread::spawn(move || {
let val = String::from("hello");
tx.send(val).unwrap();
let msgs = vec!["aaaa", "qwer", "rty", "byebye", "zaas"];
for msg in msgs {
match tx.send(String::from(msg)) {
Err(err) => {
println!("发送失败 {:?}", err);
break;
}
_ => {}
}
thread::sleep(Duration::from_micros(20));
}
});
let thandle1 = thread::spawn(move || {
let val = String::from("hello");
tx1.send(val).unwrap();
let msgs = vec!["aaaa1", "qwer1", "rty1", "byebye1", "zaas1"];
for msg in msgs {
match tx1.send(String::from(msg)) {
Err(err) => {
println!("发送失败 {:?}", err);
break;
}
_ => {}
}
thread::sleep(Duration::from_micros(5));
}
});
let handle1 = thread::spawn(move || loop {
let val = match rx.try_recv() {
Ok(msg) => msg,
Err(_) => {
thread::sleep(Duration::from_millis(10));
continue;
}
};
// let val = rx.recv().unwrap();
if val == "byebye" {
drop(rx);
break;
}
println!("receive a msg: {}", val);
});
handle.join().unwrap();
thandle1.join().unwrap();
handle1.join().unwrap();
}