1# Asynchronous Lock
2
3To solve the data contention problem between multi-thread concurrent tasks, ArkTS introduces the asynchronous lock capability. An asynchronous lock may be held by a class object. Therefore, to facilitate obtaining of the same asynchronous lock object between concurrent instances, the [AsyncLock object](../reference/apis-arkts/js-apis-arkts-utils.md#asynclock) supports cross-thread reference transfer.
4
5ArkTS supports asynchronous operations, and blocking locks are prone to deadlocks. Therefore, only asynchronous locks (non-blocking locks) are used in ArkTS. In addition, the asynchronous lock may be further used to ensure time sequence consistency of asynchronous tasks in a single thread, to prevent a synchronization problem caused by an uncertain time sequence of the asynchronous tasks.
6
7For more APIs related to asynchronous locks, see [ArkTSUtils.locks](../reference/apis-arkts/js-apis-arkts-utils.md#arktsutilslocks).
8
9> **Note**
10>
11> The method that uses an asynchronous lock must be marked as **async**, and the caller must use **await** in the call to ensure the correct call sequence.
12
13## Example
14
15To solve the contention problem caused by the modification of shared variables in different threads of the [@Sendable object](arkts-sendable.md), asynchronous locks can be used for data protection. Example:
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 the data to be protected.
27    return this.lock_.lockAsync(() => {
28      return this.count_;
29    })
30  }
31
32  public async increaseCount() {
33    // Add an asynchronous lock to the data to be protected.
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          // Transfer instance a to the subthread.
64          await taskpool.execute(printCount, a);
65        })
66    }
67    .height('100%')
68    .width('100%')
69  }
70}
71```
72