• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Asynchronous Lock
2
3To address data race issues in concurrent multithreading instances, ArkTS introduces asynchronous locks. These locks can be held by class objects. To simplify access across concurrent instances, the [AsyncLock object](../reference/apis-arkts/js-apis-arkts-utils.md#asynclock) supports pass-by-reference across threads.
4
5Given that ArkTS supports asynchronous operations, blocking locks are prone to deadlocks. Therefore, ArkTS only supports asynchronous locks (non-blocking locks). In addition, asynchronous locks can ensure the temporal consistency of asynchronous tasks within a single thread, preventing synchronization issues caused by uncertain task timing.
6
7For more details about asynchronous lock APIs, see [ArkTSUtils.locks](../reference/apis-arkts/js-apis-arkts-utils.md#arktsutilslocks).
8
9> **NOTE**
10>
11> Methods using asynchronous locks must be marked as **async**, and the caller must use the **await** keyword to ensure correct timing.
12
13## Usage Example
14
15To prevent data races when modifying shared variables across threads with [@Sendable objects](arkts-sendable.md), asynchronous locks can be used for data protection. The sample code is as follows:
16
17```ts
18import { ArkTSUtils, taskpool } from '@kit.ArkTS';
19
20@Sendable
21export class A {
22  private count_: number = 0;
23  lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock();
24
25  public async getCount(): Promise<number> {
26    // Add an asynchronous lock to protect the data.
27    return this.lock_.lockAsync(() => {
28      return this.count_;
29    })
30  }
31
32  public async increaseCount() {
33    // Add an asynchronous lock to protect the data.
34    await this.lock_.lockAsync(() => {
35      this.count_++;
36    })
37  }
38}
39
40@Concurrent
41async function printCount(a: A) {
42  console.info("InputModule: count is:" + await a.getCount());
43}
44
45@Entry
46@Component
47struct Index {
48  @State message: string = 'Hello World';
49
50  build() {
51    RelativeContainer() {
52      Text(this.message)
53        .id('HelloWorld')
54        .fontSize(50)
55        .fontWeight(FontWeight.Bold)
56        .alignRules({
57          center: { anchor: '__container__', align: VerticalAlign.Center },
58          middle: { anchor: '__container__', align: HorizontalAlign.Center }
59        })
60        .onClick(async () => {
61          // Create the Sendable object a.
62          let a: A = new A();
63          // Pass object a to a child thread.
64          await taskpool.execute(printCount, a);
65        })
66    }
67    .height('100%')
68    .width('100%')
69  }
70}
71```
72<!-- @[example_protect](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/ArktsAsyncLockIntroduction.ets) -->
73