• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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共享模块是进程内只会加载一次的模块,使用"use shared"这一指令来标记一个模块是否为共享模块。
10
11非共享模块在同一线程内只加载一次,而在不同线程中会多次加载,每个线程都会生成新的模块对象。因此,目前只能使用共享模块实现进程单例。
12
13
14## 约束限制
15
16- "use shared"需要与"use strict"一样写在ArkTS文件顶层,写在import语句之后其他语句之前。
17
18  共享属性不具备传递性。非共享模块A即使引入了共享模块B,也不会因此变成共享模块。
19
20
21- 共享模块只支持ets文件。
22
23- 共享模块内不允许使用side-effects-import。
24
25  共享模块在同一进程内仅加载一次,可在不同线程间共享。<br/>
26  共享模块加载时,导入的非共享模块不会立即加载。在共享模块内访问依赖的非共享模块导出变量时,当前线程会懒加载对应的非共享模块。非共享模块在线程间隔离,不同线程访问时会进行一次懒加载。<br/>
27  由于side-effects-import不涉及导出变量,因此不会被加载,也不受支持。
28  ```ts
29  // test.ets
30  console.info("This runs immediately when imported");
31  ```
32
33  ```ts
34  // sharedModule.ets
35  // 不允许使用side-effects-import,编译报错
36  import "./test";
37  "use shared"
38  ```
39
40- 共享模块导出的变量必须是可共享对象。
41
42  共享模块在并发实例间可共享,因此导出的所有对象必须是可共享的。可共享对象参考[Sendable支持的数据类型](arkts-sendable.md#sendable支持的数据类型)。
43
44- 共享模块不支持re-export写法。
45
46  ```ts
47  // test.ets
48  export let num = 1;
49  export let str = 'aaa';
50  ```
51
52  ```ts
53  // share.ets
54  // 共享模块
55  'use shared'
56  export * from './test'; // 编译报错
57  export {num, str} from './test'; // 产生运行时报错
58  ```
59
60
61- 共享模块可以引用其他共享模块或非共享模块,引用和被引用场景没有限制。
62
63- 仅支持使用静态加载、napi_load_module或napi_load_module_with_info加载共享模块。
64  ```ts
65  // test.ets
66  import { num } from './A'; // 支持静态加载
67
68  import { worker } from '@kit.ArkTS';
69  let wk = new worker.ThreadWorker("./A"); // 不支持其他方式加载共享模块, 将产生运行时报错
70  ```
71  ```ts
72  // A.ets
73  'use shared'
74  export let num: number = 10;
75  ```
76
77## 使用示例
78
791. 共享模块导出Sendable对象。
80
81   ```ts
82   // 共享模块sharedModule.ets
83   import { ArkTSUtils } from '@kit.ArkTS';
84
85   // 声明当前模块为共享模块,只能导出可Sendable数据
86   "use shared"
87
88   // 共享模块,SingletonA全局唯一
89   @Sendable
90   class SingletonA {
91     private count_: number = 0;
92     lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock()
93
94     public async getCount(): Promise<number> {
95       return this.lock_.lockAsync(() => {
96         return this.count_;
97       })
98     }
99
100     public async increaseCount() {
101       await this.lock_.lockAsync(() => {
102         this.count_++;
103       })
104     }
105   }
106
107   export let singletonA = new SingletonA();
108   ```
109   <!-- @[export_sendable_object](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/sharedModule.ets) -->
110
1112. 在多个线程中操作共享模块导出的对象。
112
113   ```ts
114   import { taskpool } from '@kit.ArkTS';
115   import { singletonA } from './sharedModule';
116
117   @Concurrent
118   async function increaseCount() {
119     await singletonA.increaseCount();
120     console.info("SharedModule: count is:" + await singletonA.getCount());
121   }
122
123   @Concurrent
124   async function printCount() {
125     console.info("SharedModule: count is:" + await singletonA.getCount());
126   }
127
128   @Entry
129   @Component
130   struct Index {
131     @State message: string = 'Hello World';
132
133     build() {
134       Row() {
135         Column() {
136           Button("MainThread print count")
137             .onClick(async () => {
138               await printCount();
139             })
140           Button("Taskpool print count")
141             .onClick(async () => {
142               await taskpool.execute(printCount);
143             })
144           Button("MainThread increase count")
145             .onClick(async () => {
146               await increaseCount();
147             })
148           Button("Taskpool increase count")
149             .onClick(async () => {
150               await taskpool.execute(increaseCount);
151             })
152         }
153         .width('100%')
154       }
155       .height('100%')
156     }
157   }
158   ```
159   <!-- @[ multi_thread_operate_exported_obj](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/ArkTsConcurrent/ConcurrentThreadCommunication/InterThreadCommunicationObjects/SendableObject/SendableObjectRelated/entry/src/main/ets/managers/ArktsSendableModule.ets) -->
160