目录

Shared Module

A shared module, marked with use shared, is loaded only once in a process.

A non-shared module is loaded once in the same thread and multiple times in different threads, creating a new module object in each thread. Currently, only shared modules can be used to implement process-wide singletons.

Constraints

Usage Example

  1. Export a Sendable object from a shared module.

    // Shared module sharedModule.ets
    import { ArkTSUtils } from '@kit.ArkTS';
    
    // Declare the current module as shared. Only Sendable data can be exported.
    "use shared"
    
    // Shared module. SingletonA is globally unique.
    @Sendable
    class SingletonA {
      private count_: number = 0;
      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. Operate an object exported from the shared module across multiple threads.

    import { 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';
    
      build() {
        Row() {
          Column() {
            Button("MainThread print count")
              .onClick(async () => {
                await printCount();
              })
            Button("Taskpool print count")
              .onClick(async () => {
                await taskpool.execute(printCount);
              })
            Button("MainThread increase count")
              .onClick(async () => {
                await increaseCount();
              })
            Button("Taskpool increase count")
              .onClick(async () => {
                await taskpool.execute(increaseCount);
              })
          }
          .width('100%')
        }
        .height('100%')
      }
    }