Skip to content

Instantly share code, notes, and snippets.

@wayslog
Created July 17, 2017 08:28
Show Gist options
  • Save wayslog/d2be68440dd246fc01cec1a90033a510 to your computer and use it in GitHub Desktop.
Save wayslog/d2be68440dd246fc01cec1a90033a510 to your computer and use it in GitHub Desktop.
rust locker and context switch
#![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