duskphantom_utils/
paral_counter.rs

1// Copyright 2024 Duskphantom Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// SPDX-License-Identifier: Apache-2.0
16
17//高并发id分配器,用于分配虚拟寄存器使用的id
18use std::sync::atomic::{AtomicUsize, Ordering};
19use std::sync::Arc;
20// 能够高并发地管理一定 数据范围内的id分配
21#[derive(Debug, Clone)]
22pub struct ParalCounter {
23    end: usize,
24    counter: Arc<AtomicUsize>,
25}
26
27impl ParalCounter {
28    pub fn new(start: usize, end: usize) -> Self {
29        Self {
30            end,
31            counter: Arc::new(AtomicUsize::new(start)),
32        }
33    }
34    pub fn get_id(&self) -> Option<usize> {
35        let id = self.counter.fetch_add(1, Ordering::SeqCst);
36        if id < self.end {
37            Some(id)
38        } else {
39            None
40        }
41    }
42}