• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Shared Module
2
3A shared module, marked with **use shared**, is loaded only once in a process.
4
5A 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.
6
7
8## Constraints
9
10- Similar to **use strict**, **use shared** must be placed at the top level of ArkTS files and should appear after **import** statements but before any other code.
11
12  The shared property cannot be passed on. That is, importing a shared module does not make a non-shared module shared.
13
14
15- Shared modules are only supported in .ets files.
16
17- **side-effects-import** is not allowed in shared modules.
18
19  A shared module is loaded only once within a single process and can be used across multiple threads.
20
21  When a shared module is loaded, non-shared modules that it imports are not loaded immediately. Instead, these non-shared modules are lazy-imported within the current thread when their exported variables are accessed. This lazy loading ensures that non-shared modules remain isolated between threads, with each thread potentially loading the module once if needed.
22
23  side-effects-import, which does not involve exported variables, is never loaded and therefore is not supported.
24
25  ```ts
26  // side-effects-import is not allowed.
27  import "./sharedModule";
28  ```
29
30- All variables exported by shared modules must be Sendable objects.
31
32  Since shared modules are shared across concurrent instances, all exported objects must be Sendable. For details, see [Sendable Data Types](arkts-sendable.md#sendable-data-types).
33
34- Modules cannot be directly exported from a shared module.
35
36  ```ts
37  // test.ets
38  export let num = 1;
39  export let str = 'aaa';
40  ```
41
42  ```ts
43  // share.ets
44  // Shared module
45  'use shared'
46  export * from './test'; // A compile-time error is reported. The module cannot be directly exported.
47  export {num, str} from './test'; // Correct example. Export the object set.
48  ```
49
50
51- Shared modules can import or be imported by both shared and non-shared modules. There are no restrictions on importing or being imported by shared modules.
52
53- Only static loading, **napi_load_module**, or **napi_load_module_with_info** can be used to load shared modules.
54  ```ts
55  // test.ets
56  import { num } from './A'; // Static loading is supported.
57
58  import worker from '@ohos.worker';
59  let wk = new worker.ThreadWorker("./A"); // Other methods of loading shared modules are not supported and will result in runtime errors.
60
61  // A.ets
62  'use shared'
63
64  export {num, str} from './test';
65  ```
66
67## Usage Example
68
691. Export a Sendable object from a shared module.
70
71   ```ts
72   // Shared module sharedModule.ets
73   import { ArkTSUtils } from '@kit.ArkTS';
74
75   // Declare the current module as shared. Only Sendable data can be exported.
76   "use shared"
77
78   // Shared module. SingletonA is globally unique.
79   @Sendable
80   class SingletonA {
81     private count_: number = 0;
82     lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock()
83
84     public async getCount(): Promise<number> {
85       return this.lock_.lockAsync(() => {
86         return this.count_;
87       })
88     }
89
90     public async increaseCount() {
91       await this.lock_.lockAsync(() => {
92         this.count_++;
93       })
94     }
95   }
96
97   export let singletonA = new SingletonA();
98   ```
99   <!-- @[export_sendable_object](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/sharedModule.ets) -->
100
1012. Operate an object exported from the shared module across multiple threads.
102
103   ```ts
104   import { taskpool } from '@kit.ArkTS';
105   import { singletonA } from './sharedModule';
106
107   @Concurrent
108   async function increaseCount() {
109     await singletonA.increaseCount();
110     console.info("SharedModule: count is:" + await singletonA.getCount());
111   }
112
113   @Concurrent
114   async function printCount() {
115     console.info("SharedModule: count is:" + await singletonA.getCount());
116   }
117
118   @Entry
119   @Component
120   struct Index {
121     @State message: string = 'Hello World';
122
123     build() {
124       Row() {
125         Column() {
126           Button("MainThread print count")
127             .onClick(async () => {
128               await printCount();
129             })
130           Button("Taskpool print count")
131             .onClick(async () => {
132               await taskpool.execute(printCount);
133             })
134           Button("MainThread increase count")
135             .onClick(async () => {
136               await increaseCount();
137             })
138           Button("Taskpool increase count")
139             .onClick(async () => {
140               await taskpool.execute(increaseCount);
141             })
142         }
143         .width('100%')
144       }
145       .height('100%')
146     }
147   }
148   ```
149   <!-- @[ multi_thread_operate_exported_obj](https://gitee.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/ArktsSendableModule.ets) -->
150