1# 异步锁 2<!--Kit: ArkTS--> 3<!--Subsystem: CommonLibrary--> 4<!--Owner: @lijiamin2025--> 5<!--Designer: @weng-changcheng--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @ge-yafang--> 8 9为了解决多线程并发实例间的数据竞争问题,ArkTS引入了异步锁能力。异步锁可能会被类对象持有,因此为了更方便地在并发实例间获取同一个异步锁对象,[AsyncLock对象](../reference/apis-arkts/arkts-apis-arkts-utils-locks.md#asynclock)支持跨线程引用传递。 10 11由于ArkTS语言支持异步操作,阻塞锁容易产生死锁问题,因此在ArkTS中仅支持异步锁(非阻塞式锁)。同时,异步锁还可以用于保证单线程内的异步任务时序一致性,防止异步任务时序不确定导致的同步问题。 12 13更多异步锁相关接口,请参见[异步锁ArkTSUtils.locks](../reference/apis-arkts/arkts-apis-arkts-utils-locks.md)。 14 15> **说明:** 16> 17> 使用异步锁的方法需标记为async,调用时需用await修饰,以确保时序正确。 18 19## 使用示例 20 21为了防止[@Sendable共享对象](arkts-sendable.md)在不同线程中修改共享变量导致的竞争问题,可以使用异步锁保护数据。示例如下: 22 23```ts 24import { ArkTSUtils, taskpool } from '@kit.ArkTS'; 25 26@Sendable 27export class A { 28 private count_: number = 0; 29 lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); 30 31 public getCount(): Promise<number> { 32 // 对需要保护的数据加异步锁 33 return this.lock_.lockAsync(() => { 34 return this.count_; 35 }) 36 } 37 38 public async increaseCount() { 39 // 对需要保护的数据加异步锁 40 await this.lock_.lockAsync(() => { 41 this.count_++; 42 }) 43 } 44} 45 46@Concurrent 47async function printCount(a: A) { 48 a.increaseCount(); 49 console.info("InputModule: count is:" + await a.getCount()); 50} 51 52@Entry 53@Component 54struct Index { 55 @State message: string = 'Hello World'; 56 57 build() { 58 RelativeContainer() { 59 Text(this.message) 60 .id('HelloWorld') 61 .fontSize(50) 62 .fontWeight(FontWeight.Bold) 63 .alignRules({ 64 center: { anchor: '__container__', align: VerticalAlign.Center }, 65 middle: { anchor: '__container__', align: HorizontalAlign.Center } 66 }) 67 .onClick(async () => { 68 // 创建sendable对象a 69 let a: A = new A(); 70 // 将实例a传递给子线程 71 await taskpool.execute(printCount, a); 72 }) 73 } 74 .height('100%') 75 .width('100%') 76 } 77} 78``` 79<!-- @[example_protect](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/ArktsAsyncLockIntroduction.ets) -->