目录

共享模块

共享模块是进程内只会加载一次的模块,使用'use shared'这一指令来标记一个模块是否为共享模块。

非共享模块在同一线程内只加载一次,而在不同线程中会多次加载,每个线程都会生成新的模块对象。因此,目前只能使用共享模块实现进程单例。

约束限制

使用示例

  1. 共享模块导出Sendable对象。

    // 共享模块
    import { ArkTSUtils } from '@kit.ArkTS';
    
    // 声明当前模块为共享模块,只能导出Sendable数据
    'use shared'
    
    // 共享模块,singletonA全局唯一
    @Sendable
    class SingletonA {
      private count_: number = 0;
      public lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock();
    
      public async getCount(): Promise<number> {
        return this.lock_.lockAsync(() => {
          return this.count_;
        })
      }
    
      public async increaseCount() {
        await this.lock_.lockAsync(() => {
          this.count_++;
        })
      }
    }
    
    export let singletonA = new SingletonA();
  2. 在多个线程中操作共享模块导出的对象。

    import { ArkTSUtils, taskpool } from '@kit.ArkTS';
    import { singletonA } from './sharedModule';
    
    // ...
    
    @Concurrent
    async function increaseCount() {
      await singletonA.increaseCount();
      console.info(`SharedModule: count is: ${await singletonA.getCount()}`);
    }
    
    @Concurrent
    async function printCount() {
      console.info(`SharedModule: count is: ${await singletonA.getCount()}`);
    }
    
    @Entry
    @Component
    struct Index {
      @State message: string = 'Hello World';
      @State mainThreadPrint: string = 'MainThread print count';
      @State taskpoolPrint: string = 'Taskpool print count';
      @State mainThreadIncrease: string = 'MainThread increase count';
      @State taskpoolIncrease: string = 'Taskpool increase count';
    
      build() {
        Row() {
          Column() {
            Button(this.mainThreadPrint)
              .id('MainThread print count')
              .onClick(async () => {
                await printCount();
                this.mainThreadPrint = 'success';
              })
            Button(this.taskpoolPrint)
              .id('Taskpool print count')
              .onClick(async () => {
                await taskpool.execute(printCount);
                this.taskpoolPrint = 'success';
              })
            Button(this.mainThreadIncrease)
              .id('MainThread increase count')
              .onClick(async () => {
                await increaseCount();
                this.mainThreadIncrease = 'success';
              })
            Button(this.taskpoolIncrease)
              .id('Taskpool increase count')
              .onClick(async () => {
                await taskpool.execute(increaseCount);
                this.taskpoolIncrease = 'success';
              })
          }
          .width('100%')
        }
        .height('100%')
      }
    }