mirror of
https://github.com/romanz/electrs.git
synced 2025-02-24 15:02:21 +01:00
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.
This commit is contained in:
parent
9df66d97e3
commit
2a835d94ef
1 changed files with 5 additions and 6 deletions
|
@ -13,7 +13,7 @@ use std::collections::{HashMap, HashSet};
|
||||||
use std::io::{BufRead, BufReader, Lines, Write};
|
use std::io::{BufRead, BufReader, Lines, Write};
|
||||||
use std::net::{SocketAddr, TcpStream};
|
use std::net::{SocketAddr, TcpStream};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::errors::*;
|
use crate::errors::*;
|
||||||
|
@ -267,20 +267,19 @@ impl Connection {
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Counter {
|
struct Counter {
|
||||||
value: Mutex<u64>,
|
value: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Counter {
|
impl Counter {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Counter {
|
Counter {
|
||||||
value: Mutex::new(0),
|
value: 0.into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next(&self) -> u64 {
|
fn next(&self) -> u64 {
|
||||||
let mut value = self.value.lock().unwrap();
|
// fetch_add() returns previous value, we want current one
|
||||||
*value += 1;
|
self.value.fetch_add(1, Ordering::Relaxed) + 1
|
||||||
*value
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue