os/kernel/task/
tid_allocator.rs1use core::sync::atomic::AtomicU32;
4
5#[derive(Debug)]
9pub struct TidAllocator {
10 next_tid: AtomicU32,
11}
12
13impl TidAllocator {
14 pub const fn new() -> Self {
16 TidAllocator {
17 next_tid: AtomicU32::new(1),
18 }
19 }
20
21 pub fn allocate(&self) -> u32 {
23 self.next_tid
24 .fetch_add(1, core::sync::atomic::Ordering::SeqCst)
25 }
26}
27
28#[cfg(test)]
29mod tests {
30 use super::*;
31 use crate::{kassert, test_case};
32
33 test_case!(test_tid_allocate_sequence, {
35 let alloc = TidAllocator::new();
36 kassert!(alloc.allocate() == 1);
37 kassert!(alloc.allocate() == 2);
38 kassert!(alloc.allocate() == 3);
39 });
40
41 test_case!(test_tid_allocate_multiple_refs, {
43 let alloc = TidAllocator::new();
44 let a1 = alloc.allocate();
45 let a2 = alloc.allocate();
46 kassert!(a1 == 1);
47 kassert!(a2 == 2);
48
49 let r = &alloc;
51 let a3 = r.allocate();
52 kassert!(a3 == 3);
53 });
54}