• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
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 */
15import { HiLog } from './HiLog';
16
17const TAG = 'CounterLock';
18
19export default class CounterLock {
20  private locked: boolean = false;
21  private queue: Array<() => void> = [];
22
23  async acquire(): Promise<void> {
24    return new Promise((resolve) => {
25      const tryAcquire = () => {
26        if (!this.locked) {
27          this.locked = true;
28          resolve();
29        } else {
30          this.queue.push(() => {
31            try {
32              tryAcquire();
33            } catch (err) {
34              HiLog.wrapError(TAG, err, 'Error occurred while tryAcquire');
35              this.release();
36            }
37          });
38        }
39      };
40      tryAcquire();
41    });
42  }
43
44  release(): void {
45    if (this.queue.length > 0) {
46      const next = this.queue.shift();
47      try {
48        next?.();
49      } catch (err) {
50        HiLog.wrapError(TAG, err, 'Error occurred while executing task');
51        this.release();
52      }
53    } else {
54      this.locked = false;
55    }
56  }
57}