Browse Source

Use atomic u64 instead of Mutex for counter

This change switches from `Mutex<u64>` to `AtomicU64`, which is faster
and somewhat more elegant to write. It keeps the `Counter` type for
backwards compatibility.

The downside is that it doesn't work on as many platforms and requires
fairly recent compiler.
atomic_counter
Martin Habovstiak 5 years ago
parent
commit
2a835d94ef
  1. 11
      src/daemon.rs

11
src/daemon.rs

@ -13,7 +13,7 @@ use std::collections::{HashMap, HashSet};
use std::io::{BufRead, BufReader, Lines, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}};
use std::time::Duration;
use crate::errors::*;
@ -267,20 +267,19 @@ impl Connection {
}
struct Counter {
value: Mutex<u64>,
value: AtomicU64,
}
impl Counter {
fn new() -> Self {
Counter {
value: Mutex::new(0),
value: 0.into(),
}
}
fn next(&self) -> u64 {
let mut value = self.value.lock().unwrap();
*value += 1;
*value
// fetch_add() returns previous value, we want current one
self.value.fetch_add(1, Ordering::Relaxed) + 1
}
}

Loading…
Cancel
Save