Created
July 17, 2017 08:28
-
-
Save wayslog/d2be68440dd246fc01cec1a90033a510 to your computer and use it in GitHub Desktop.
rust locker and context switch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(test)] | |
extern crate test; | |
#[bench] | |
fn test_lock(b: &mut test::Bencher) { | |
use std::sync::Mutex; | |
let locker = Mutex::new(1u32); | |
b.iter(|| { | |
for _ in 0..1000 { | |
let mut number = locker.lock().unwrap(); | |
*number += 1; | |
} | |
}); | |
} | |
fn lock_concurrency(worker: u32) { | |
use std::sync::{Mutex, Arc}; | |
use std::thread; | |
let locker = Arc::new(Mutex::new(0u32)); | |
let ths = (0..worker).into_iter().map(|_| { | |
let locker = locker.clone(); | |
thread::spawn(move || { | |
for _ in 0..1000 { | |
let mut number = locker.lock().unwrap(); | |
*number += 1; | |
} | |
}) | |
}); | |
for th in ths { | |
th.join().unwrap(); | |
} | |
} | |
#[bench] | |
fn test_lock_in_1_thread(b: &mut test::Bencher) { | |
b.iter(|| { | |
lock_concurrency(1); | |
}) | |
} | |
#[bench] | |
fn test_lock_in_4_thread(b: &mut test::Bencher) { | |
b.iter(|| { | |
lock_concurrency(4); | |
}) | |
} | |
#[bench] | |
fn test_lock_in_10_thread(b: &mut test::Bencher) { | |
b.iter(|| { | |
lock_concurrency(10); | |
}) | |
} | |
fn main() {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment