戳人痛处

导航

[记]tokio学习

spawn_blocking

use std::thread;
use std::time;
use tokio::time::{sleep,Duration};
fn blocking_call() -> String{
    for idx in 0..5{
        thread::sleep(time::Duration::from_secs(1));
        println!("---{}",idx);
    }
    
    "Finally done".to_string()
}

async fn async_call(id: i32){
    sleep(Duration::from_secs(1)).await;
    println!("Async id:{}",id);
}

#[tokio::main]
async fn main() {
    let blocking_call_handle = tokio::task::spawn_blocking(blocking_call);
    let mut async_handles = Vec::new();
    for id in 0..10{
        async_handles.push(tokio::spawn(async_call(id)));
    }

    for handle in async_handles{
        handle.await.unwrap();
    }
    println!("Hello, world!");
    let result = blocking_call_handle.await.unwrap();
    println!("Blocking result:{}",result);
}

---0
Async id:2
Async id:7
Async id:6
Async id:0
Async id:3
Async id:9
Async id:4
Async id:5
Async id:8
Async id:1
Hello, world!
---1
---2
---3
---4
Blocking result:Finally done

Arc

use std::sync::Arc;

use tokio::sync::Mutex;
use tokio::time::{sleep,Duration};

async fn person(remote_arc: Arc<Mutex<i32>>, name: String, new_channel: i32){
    // request access to the remote
    let mut real_remote = remote_arc.lock().await;

    // Chaning the tv channel
    *real_remote = new_channel;
    println!("{} changed the channel", name);
    println!("Watching channel: {}", new_channel);

    sleep(Duration::from_secs(5)).await;
}
#[tokio::main]
async fn main(){
    let tv_channel = 10;
    let remote = Mutex::new(tv_channel);
    let remote_arc = Arc::new(remote);

    let mut task_handles = Vec::new();

    for (name,new_channel) in [("Marcus",11),("Jovanna",32),("Carmen",43)]{
        task_handles.push(tokio::spawn(person(remote_arc.clone(), name.to_string(), new_channel)));
    }

    for handle in task_handles{
        handle.await.unwrap();
    }
}
Marcus changed the channel
Watching channel: 11
Jovanna changed the channel
Watching channel: 32
Carmen changed the channel
Watching channel: 43

Semaphore

use std::sync::Arc;

use tokio::sync::Semaphore;
use tokio::time::{sleep,Duration};

async fn person(semaphore: Arc<Semaphore>, name: String){
    println!("{} is waiting in line", name);

    teller(semaphore, name).await;
}

async fn teller(semaphore: Arc<Semaphore>, customer: String){
    let permit = semaphore.acquire().await.unwrap();

    sleep(Duration::from_secs(2)).await;
    println!("\n{} is being served by the teller",customer);
    sleep(Duration::from_secs(5)).await;
    println!("{} is now leaving the teller",customer);

    drop(permit)
}

#[tokio::main]
async fn main(){
    let num_of_tellers = 4;
    let semaphore = Semaphore::new(num_of_tellers);
    let semaphore_arc = Arc::new(semaphore);

    let mut people_handles = Vec::new();
    for num in 0..10{
        people_handles.push(
            tokio::spawn(person(semaphore_arc.clone(), num.to_string()))
        );
    }

    for handle in people_handles{
        handle.await.unwrap();
    }
}
0 is waiting in line
1 is waiting in line
2 is waiting in line
4 is waiting in line
5 is waiting in line
6 is waiting in line
7 is waiting in line
8 is waiting in line
9 is waiting in line
3 is waiting in line

2 is being served by the teller

0 is being served by the teller

4 is being served by the teller

1 is being served by the teller
4 is now leaving the teller
0 is now leaving the teller
2 is now leaving the teller
1 is now leaving the teller

7 is being served by the teller

5 is being served by the teller

8 is being served by the teller

6 is being served by the teller
8 is now leaving the teller
6 is now leaving the teller
7 is now leaving the teller
5 is now leaving the teller

9 is being served by the teller

3 is being served by the teller
9 is now leaving the teller
3 is now leaving the teller

Notify

use std::sync::Arc;

use tokio::sync::Notify;
use tokio::time::{sleep,Duration};

async fn order_package(package_delivered: Arc<Notify>){
    sleep(Duration::from_secs(2)).await;
    println!("Find package in warehouse");

    sleep(Duration::from_secs(2)).await;
    println!("Ship package");

    sleep(Duration::from_secs(2)).await;
    println!("Package has been delivered");
    package_delivered.notify_one();
}

async fn grab_package(package_delivered: Arc<Notify>){
    package_delivered.notified().await;
    println!("Look outside house for package");
    sleep(Duration::from_secs(2)).await;
    println!("Grab package");
}

#[tokio::main]
async fn main(){
    let package_delivered = Notify::new();
    let package_delivered_arc = Arc::new(package_delivered);

    let order_package_handle = tokio::spawn(
        order_package(package_delivered_arc.clone())
    );

    let grab_package_handle = tokio::spawn(
        grab_package(package_delivered_arc.clone())
    );

    order_package_handle.await.unwrap();
    grab_package_handle.await.unwrap();
}
Find package in warehouse
Ship package
Package has been delivered
Look outside house for package
Grab package

Barrier

use std::sync::Arc;

use tokio::sync::{Barrier, BarrierWaitResult, Notify};
use tokio::time::{sleep, Duration};

async fn barrier_example(barrier: Arc<Barrier>, notify: Arc<Notify>) -> BarrierWaitResult{
    println!("Waiting at barrier");

    let wait_result = barrier.wait().await;
    println!("Passed through the barrier");

    if wait_result.is_leader(){
        notify.notify_one();
    }

    wait_result
}

#[tokio::main]
async fn main(){
    let total_cans_needed = 12;
    let barrier = Arc::new(Barrier::new(total_cans_needed));

    let notify = Arc::new(Notify::new());

    //To send the first batch of cans to the barrier
    notify.notify_one();
    let mut task_handles = Vec::new();

    for can_count in 0..60{
        if can_count % 12 == 0{
            notify.notified().await;

            // Give the barrier some time close
            sleep(Duration::from_millis(1)).await;
        }

        task_handles.push(tokio::spawn(
            barrier_example(barrier.clone(), notify.clone())
        ))

    }
    let mut num_of_leaders = 0;
    for handle in task_handles{
        let wait_result = handle.await.unwrap();

        if wait_result.is_leader(){
            num_of_leaders += 1;
        }
    }

    println!("total num of leaders: {}", num_of_leaders);
}
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Waiting at barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
Passed through the barrier
total num of leaders: 5

RwLock

use std::sync::Arc;

use tokio::sync::RwLock;
use tokio::time::{sleep,Duration};

async fn read_from_document(id: i32, document: Arc<RwLock<String>>){
    let reader = document.read().await;

    println!("reader_{}: {}", id, reader);
}

async fn write_to_document(document: Arc<RwLock<String>>, new_string: &str){
    let mut writer = document.write().await;
    println!("write {}",new_string);
    writer.push_str(new_string);
    writer.push_str(" ");
}

#[tokio::main]
async fn main(){
    let document = Arc::new(RwLock::new("".to_string()));

    let mut handles = Vec::new();
    for new_string in "I can read and write a b c d e f h i j k l m n o p q r s t u v w x y z"
    .split_whitespace(){
        handles.push(tokio::spawn(read_from_document(1, document.clone())));
        
        handles.push(tokio::spawn(write_to_document(document.clone(), new_string)));
    
        handles.push(tokio::spawn(read_from_document(2, document.clone())));
        
        handles.push(tokio::spawn(read_from_document(3, document.clone())));
    }

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

}
reader_1: 
write I
reader_1: I
reader_2: I
reader_3: I
write can
reader_1: I can
reader_2: I can
reader_3: I can
write read
reader_1: I can read
reader_2: I can read
reader_3: I can read
write and
reader_1: I can read and
reader_2: I can read and
reader_3: I can read and
write write
reader_3: I can read and write
reader_2: I can read and write
write a
reader_1: I can read and write a
reader_2: I can read and write a
reader_1: I can read and write a
reader_3: I can read and write a
write c
reader_1: I can read and write a c
reader_2: I can read and write a c
reader_3: I can read and write a c
write d
reader_1: I can read and write a c d
reader_2: I can read and write a c d
reader_3: I can read and write a c d
write e
reader_1: I can read and write a c d e
reader_2: I can read and write a c d e
reader_3: I can read and write a c d e
write f
reader_2: I can read and write a c d e f
reader_3: I can read and write a c d e f
reader_1: I can read and write a c d e f
write h
reader_2: I can read and write a c d e f h
reader_1: I can read and write a c d e f h
write b
reader_2: I can read and write a c d e f h b 
reader_3: I can read and write a c d e f h b
reader_3: I can read and write a c d e f h b
reader_1: I can read and write a c d e f h b
write i
reader_1: I can read and write a c d e f h b i
reader_3: I can read and write a c d e f h b i
reader_2: I can read and write a c d e f h b i
write j
reader_1: I can read and write a c d e f h b i j
reader_2: I can read and write a c d e f h b i j
reader_3: I can read and write a c d e f h b i j
write k
reader_1: I can read and write a c d e f h b i j k
reader_2: I can read and write a c d e f h b i j k
reader_3: I can read and write a c d e f h b i j k
write l
reader_1: I can read and write a c d e f h b i j k l
reader_2: I can read and write a c d e f h b i j k l
reader_3: I can read and write a c d e f h b i j k l
write m
reader_3: I can read and write a c d e f h b i j k l m
reader_1: I can read and write a c d e f h b i j k l m
reader_2: I can read and write a c d e f h b i j k l m
write n
reader_1: I can read and write a c d e f h b i j k l m n
reader_2: I can read and write a c d e f h b i j k l m n
reader_3: I can read and write a c d e f h b i j k l m n
write o
reader_2: I can read and write a c d e f h b i j k l m n o
reader_3: I can read and write a c d e f h b i j k l m n o
reader_1: I can read and write a c d e f h b i j k l m n o
write p
reader_1: I can read and write a c d e f h b i j k l m n o p
reader_2: I can read and write a c d e f h b i j k l m n o p
reader_3: I can read and write a c d e f h b i j k l m n o p
write q
reader_1: I can read and write a c d e f h b i j k l m n o p q
reader_2: I can read and write a c d e f h b i j k l m n o p q
reader_3: I can read and write a c d e f h b i j k l m n o p q
write r
reader_1: I can read and write a c d e f h b i j k l m n o p q r
reader_2: I can read and write a c d e f h b i j k l m n o p q r
reader_3: I can read and write a c d e f h b i j k l m n o p q r
write s
reader_1: I can read and write a c d e f h b i j k l m n o p q r s
reader_3: I can read and write a c d e f h b i j k l m n o p q r s 
reader_1: I can read and write a c d e f h b i j k l m n o p q r s
reader_2: I can read and write a c d e f h b i j k l m n o p q r s
reader_3: I can read and write a c d e f h b i j k l m n o p q r s
write u
reader_1: I can read and write a c d e f h b i j k l m n o p q r s u
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u
write v
reader_1: I can read and write a c d e f h b i j k l m n o p q r s u v
write w
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u v w
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u v w
reader_1: I can read and write a c d e f h b i j k l m n o p q r s u v w
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w
write x
reader_1: I can read and write a c d e f h b i j k l m n o p q r s u v w x
write y
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w x y
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u v w x y
reader_1: I can read and write a c d e f h b i j k l m n o p q r s u v w x y
write z
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w x y z
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u v w x y z
reader_3: I can read and write a c d e f h b i j k l m n o p q r s u v w x y z
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w x y z
write t
reader_2: I can read and write a c d e f h b i j k l m n o p q r s u v w x y z t

posted on 2024-06-13 10:47  戳人痛处  阅读(7)  评论(0编辑  收藏  举报