1# ArkTS Asynchronous Lock
2
3## Overview
4
5To avoid data races between concurrent instances, the ArkTS common library introduces **AsyncLock**. Passing **AsyncLock** objects by reference across concurrent instances is supported.
6
7ArkTS supports asynchronous operations, and blocking locks are prone to deadlocks. Therefore, only asynchronous locks (non-blocking locks) are used in ArkTS.
8
9For details, see [AsyncLock APIs](../reference/apis-arkts/js-apis-arkts-utils.md#arktsutilslocks).
10
11The 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. As a result, all outer functions are marked as **async**.
12
13
14## Example
15
16```ts
17// Index.ets
18import { taskpool } from '@kit.ArkTS';
19import { A, a } from './sendableTest'
20
21@Concurrent
22async function printInfo(a: A) {
23  a.increaseCount()
24  a.setName("sendableTest: this taskpool thread!")
25  console.info("sendableTest: child thread count is: " + await a.getCount() + ", name is: " + await a.getName());
26}
27
28
29async function testFunc() {
30  await taskpool.execute(printInfo, a);
31}
32
33@Entry
34@Component
35struct Index {
36  @State message: string = 'Hello World';
37
38  build() {
39    Row() {
40      Column() {
41        Button("Main thread!")
42          .fontSize(50)
43          .fontWeight(FontWeight.Bold)
44          .onClick(async () => {
45            console.info("sendableTest: Main thread count is: " + await a.getCount() + ", name is: " + await a.getName());
46          })
47        Button("taskpool thread!")
48          .fontSize(50)
49          .fontWeight(FontWeight.Bold)
50          .onClick(async () => {
51            await testFunc();
52          })
53      }
54      .width('100%')
55    }
56    .height('100%')
57  }
58}
59```
60
61```ts
62// sendableTest.ets
63import { ArkTSUtils } from '@kit.ArkTS';
64@Sendable
65export class A {
66  private count_: number = 0;
67  private name_: string = 'ClassA';
68  lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock()
69
70  public async getCount(): Promise<number> {
71    return this.lock_.lockAsync(() => {
72      return this.count_;
73    })
74  }
75
76  public async increaseCount() {
77    await this.lock_.lockAsync(() => {
78      this.count_++;
79    })
80  }
81
82  public async getName(): Promise<string> {
83    return this.lock_.lockAsync(() => {
84      return this.name_;
85    })
86  }
87
88  public async setName(name: string) {
89    await this.lock_.lockAsync(() => {
90      this.name_ = name;
91    })
92  }
93}
94
95export let a:A = new A();
96```
97