1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::{u64, usize};
use std::default::Default;
use std::fmt;
static GLOBAL_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
fn next_global() -> usize {
let mut prev = GLOBAL_COUNTER.load(Ordering::Relaxed);
loop {
assert!(prev < usize::MAX,
"Snow Crash: Go home and reevaluate your threading model!");
let old_value = GLOBAL_COUNTER.compare_and_swap(prev, prev + 1, Ordering::Relaxed);
if old_value == prev {
return prev;
} else {
prev = old_value;
}
}
}
thread_local! {
static NEXT_LOCAL_UNIQUE_ID: UnsafeCell<ProcessUniqueId> = UnsafeCell::new(ProcessUniqueId {
prefix: next_global(),
offset: 0
})
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ProcessUniqueId {
prefix: usize,
offset: u64,
}
impl fmt::Display for ProcessUniqueId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "puid-{:x}-{:x}", self.prefix, self.offset)
}
}
impl ProcessUniqueId {
#[inline]
pub fn new() -> Self {
NEXT_LOCAL_UNIQUE_ID.with(|unique_id| {
unsafe {
let next_unique_id = *unique_id.get();
(*unique_id.get()) = if next_unique_id.offset == u64::MAX {
ProcessUniqueId {
prefix: next_global(),
offset: 0,
}
} else {
ProcessUniqueId {
prefix: next_unique_id.prefix,
offset: next_unique_id.offset + 1,
}
};
next_unique_id
}
})
}
}
impl Default for ProcessUniqueId {
#[inline]
fn default() -> Self {
ProcessUniqueId::new()
}
}
#[cfg(test)]
mod test {
extern crate test;
extern crate time;
extern crate uuid;
extern crate rand;
extern crate threadpool;
use self::threadpool::ThreadPool;
use std::thread;
use std::sync::mpsc::channel;
use self::test::Bencher;
use super::{next_global, ProcessUniqueId};
use std::u64;
#[test]
fn test_unique_id_unthreaded() {
let first_unique_id = ProcessUniqueId::new();
{
use super::NEXT_LOCAL_UNIQUE_ID;
NEXT_LOCAL_UNIQUE_ID.with(|unique_id| {
unsafe { (*unique_id.get()).offset = u64::MAX - 10 }
});
}
for i in (u64::MAX - 11)..(u64::MAX) {
assert!(ProcessUniqueId::new() ==
ProcessUniqueId {
prefix: first_unique_id.prefix,
offset: i + 1,
});
}
let next = ProcessUniqueId::new();
assert!(next.prefix != first_unique_id.prefix);
assert!(next.offset == 0);
assert!(ProcessUniqueId::new() ==
ProcessUniqueId {
prefix: next.prefix,
offset: 1,
});
}
#[test]
fn test_unique_id_threaded() {
let threads: Vec<_> = (0..10).map(|_| {
thread::spawn(move || {
thread::park();
let unique_id = ProcessUniqueId::new();
assert_eq!(unique_id.offset, 0);
unique_id.prefix
})
}).collect();
for thread in &threads {
thread.thread().unpark();
}
let mut results: Vec<_> = threads.into_iter()
.map(|t| t.join().unwrap())
.collect();
results.sort();
let old_len = results.len();
results.dedup();
assert_eq!(old_len, results.len());
}
#[bench]
fn bench_next_global(b: &mut Bencher) {
b.iter(|| {
next_global();
});
}
#[bench]
fn bench_next_global_threaded(b: &mut Bencher) {
let pool = ThreadPool::new(4usize);
b.iter(|| {
let (tx, rx) = channel();
for _ in 0..4 {
let tx = tx.clone();
pool.execute(move || {
for _ in 0..1000 {
next_global();
}
tx.send(()).unwrap();
});
}
rx.iter().take(4).count();
});
}
#[bench]
fn bench_unique_id(b: &mut Bencher) {
b.iter(|| {
ProcessUniqueId::new();
});
}
#[bench]
fn bench_random_id(b: &mut Bencher) {
use self::rand::random;
b.iter(|| {
let _: u64 = random();
});
}
#[bench]
fn bench_time_id(b: &mut Bencher) {
use self::time::get_time;
b.iter(|| {
let _ = get_time();
});
}
#[bench]
fn bench_uuid(b: &mut Bencher) {
use self::uuid::Uuid;
b.iter(|| {
Uuid::new_v4();
});
}
#[bench]
fn bench_unique_id_threaded(b: &mut Bencher) {
let pool = ThreadPool::new(4usize);
b.iter(|| {
let (tx, rx) = channel();
for _ in 0..4 {
let tx = tx.clone();
pool.execute(move || {
for _ in 0..1000 {
ProcessUniqueId::new();
}
tx.send(()).unwrap();
});
}
rx.iter().take(4).count();
});
}
}