• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Persistent Worker Threads Handling Concurrent Tasks via TaskPool
2
3In ArkTS application development, you can choose between TaskPool and Worker threads for concurrent task processing, or you utilize both capabilities.
4
5This section describes how to execute concurrent tasks through TaskPool within a Worker thread.
6
71. Create a Worker thread in the main thread and send a message.
8
9   ```ts
10   // Index.ets
11   import { worker } from '@kit.ArkTS';
12
13   @Entry
14   @Component
15   struct Index {
16     @State message: string = 'Hello World';
17
18     build() {
19       RelativeContainer() {
20         Text(this.message)
21           .id('HelloWorld')
22           .fontSize($r('app.float.page_text_font_size'))
23           .fontWeight(FontWeight.Bold)
24           .alignRules({
25             center: { anchor: '__container__', align: VerticalAlign.Center },
26             middle: { anchor: '__container__', align: HorizontalAlign.Center }
27           })
28           .onClick(() => {
29             // 1. Create a Worker instance.
30             const myWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
31
32             // 2. Handle results from the Worker instance.
33             myWorker.onmessage = (e) => {
34               console.log('Main thread receives the final result:', e.data.result);
35               myWorker.terminate(); // Destroy the Worker instance.
36             };
37
38             // 3. Send a startup instruction to the Worker instance.
39             myWorker.postMessage({ type: 'start', data: 10 });
40           })
41       }
42       .height('100%')
43       .width('100%')
44     }
45   }
46   ```
47
482. Call TaskPool to execute concurrent tasks in the Worker thread.
49
50   ```ts
51   // Worker.ets
52   import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
53   import { taskpool } from '@kit.ArkTS';
54
55   const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
56   workerPort.onmessage = async (e: MessageEvents) => {
57     if (e.data.type === 'start') {
58       // Simulate data processing by the Worker instance.
59       const processedData = heavyComputation(e.data.data);
60
61       // Call TaskPool to execute concurrent tasks.
62       const task = new taskpool.Task(parallelTask, processedData);
63       const result = await taskpool.execute(task);
64       console.log('Worker thread returns result: ', result);
65
66       // Return the final result to the main thread.
67       workerPort.postMessage({
68         status: 'success',
69         result: result
70       });
71     }
72   }
73
74   function heavyComputation(base: number): number {
75     let sum = 0;
76     for (let i = 0; i < base * 10; i++) {
77       sum += Math.sqrt(i);
78     }
79     return sum;
80   }
81
82   @Concurrent
83   function parallelTask(base: number): number {
84     let total = 0;
85     for (let i = 0; i < base; i++) {
86       total += i % 2 === 0 ? i : -i;
87     }
88     console.log('TaskPool thread calculation result: ', total);
89     return total;
90   }
91   ```
92