Skip to content

Instantly share code, notes, and snippets.

@highway900
Last active July 16, 2020 09:07
Show Gist options
  • Save highway900/41d1cbaadf9a7f18b0c0fce2895bd2d1 to your computer and use it in GitHub Desktop.
Save highway900/41d1cbaadf9a7f18b0c0fce2895bd2d1 to your computer and use it in GitHub Desktop.

Revisions

  1. highway900 revised this gist Jul 16, 2020. 1 changed file with 26 additions and 0 deletions.
    26 changes: 26 additions & 0 deletions thread_spawn_multi.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    use std::thread;
    use std::sync::Arc;
    use std::sync::Mutex;

    fn main() {
    let answer = Arc::new(Mutex::new(42));
    let mut threads = vec![];

    for i in 0..5 {
    let answer_ref = answer.clone();
    let t = thread::spawn(move || {
    let mut answer = answer_ref.lock().unwrap();
    *answer = 55;
    println!("{}: {}", i, answer);
    });
    threads.push(t);
    }

    for t in threads {
    t.join().unwrap();
    }

    let ar = answer.lock().unwrap();
    assert_eq!(*ar, 55);

    }
  2. highway900 created this gist Jul 15, 2020.
    51 changes: 51 additions & 0 deletions multi_server.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    use std::sync::{RwLock};
    use futures::future;

    use actix_web::{web, App, HttpServer};


    struct AppStateWithCounter {
    counter: RwLock<i32>,
    }

    async fn write(data: web::Data<AppStateWithCounter>) -> String {
    let mut counter = data.counter.write().unwrap();
    *counter += 1;

    format!("Request number: {}", counter) // <- response with count
    }

    async fn read(data: web::Data<AppStateWithCounter>) -> String {
    let counter = data.counter.read().unwrap();

    format!("Request number: {}", counter) // <- response with count
    }

    #[actix_rt::main]
    async fn main() -> std::io::Result<()> {
    let counter = web::Data::new(AppStateWithCounter {
    counter: RwLock::new(0),
    });

    let s1 = HttpServer::new(move || {
    // move counter into the closure
    App::new()
    .app_data(counter.clone())
    .route("/", web::get().to(write))
    })
    .bind("127.0.0.1:8000")?
    .run();

    let s2 = HttpServer::new(move || {
    App::new()
    .app_data(counter.clone())
    .route("/", web::get().to(read))
    })
    .bind("127.0.0.1:9000")?
    .run();

    future::try_join(s1, s2).await;

    Ok(())

    }