1# ArkTS Common Library Development 2 3 4## Is memory isolation available between TaskPool, Worker, and ArkTS engine instances? 5 6**TaskPool** and **Worker** implement concurrency based on the actor model, which features memory isolation. As such, memory isolation is implemented between **TaskPool**, **Worker**, and ArkTS engine instances. 7 8 9## When will a TaskPool thread be destroyed in the task pool lifecycle? 10 11You do not need to manually manage the lifecycle of a task pool. If no task is executed for a certain period of time or no listening task is executed on the **TaskPool** thread, the thread may be destroyed. 12 13 14## Does TaskPool have restrictions on the task duration? 15 16The maximum task duration is 3 minutes (excluding the time used for Promise or async/await asynchronous call). 17 18 19## Which is recommended for scenarios with a large number of preloading tasks? 20 21A maximum of eight worker threads can co-exist. As such, **TaskPool** is recommended in this case. For details about the implementation features and use cases of **TaskPool** and **Worker**, see [Comparison Between Worker and TaskPool](../arkts-utils/taskpool-vs-worker.md). 22 23 24## Which is recommended in concurrent scenarios where threads need to be reused? 25 26A worker cannot execute different tasks. As such, **TaskPool** is recommended in this case. 27 28## Can I dynamically load modules (HAR, HSP, and .so modules) in TaskPool? (API version 10) 29 30Yes. **TaskPool** provides the same dynamic loading capability as the main thread. However, after a **TaskPool** thread is loaded, it cannot be reused by the main thread due to modular thread isolation. 31 32## How do I implement multithreaded data sharing? (API version 10) 33 34ArkTS uses a single-thread model and features memory isolation. Therefore, most common objects use serialization mode to implement cross-thread sharing. 35 36An object can be shared by transferring an ArrayBuffer or using a SharedArrayBuffer. 37 38**References** 39 40[Multithreaded Concurrency Overview (TaskPool and Worker)](../arkts-utils/multi-thread-concurrency-overview.md) 41 42## Cross-thread communication of JS objects depends on serialization. Is there any performance problem? (API version 10) 43 44Cross-thread object communication depends on serialization and deserialization, and the time required is related to the data volume. Therefore, you need to control the data volume to be transmitted, or use an ArrayBuffer or SharedArrayBuffer for transfer or sharing. 45 46 47## Some applications have more than 200 threads. Neither TaskPool nor Worker supports so many threads. How do I design a concurrent scheme? (API version 10) 48 49The underlying thread model interconnects with libuv. Therefore, after an application process starts, multiple I/O threads are used for I/O operations. For a JS thread, its asynchronous I/O operations are executed in the I/O threads, and it can handle other operations simultaneously. As such, this does not cause blocking and waiting issues. 50 51In addition, ArkTS provides TaskPool concurrent APIs, which are similar to the thread pool of GCD. Tasks can be executed without thread lifecycle management. 52 53To address the problem that a large number of threads are required, you are advised to: 54 55- Convert multi-thread tasks into concurrent tasks and distribute them through the task pool. 56- Execute I/O tasks in the calling thread (which can be the **TaskPool** thread), rather than starting new threads for them. 57- Use worker threads (no more than 8) for resident CPU intensive tasks (which is of a small number). 58 59**References** 60 61[Comparison Between TaskPool and Worker](../arkts-utils/taskpool-vs-worker.md) 62 63## How do I set task priorities, what are the differences between scheduling policies for these priorities, and what are the recommended scenarios for them? (API version 10) 64 65You can set different priorities for different tasks. 66 67**Sample Code** 68 69```ts 70@Concurrent 71function printArgs(args: number): number { 72 console.log("printArgs: " + args); 73 return args; 74} 75 76let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number 77let highCount = 0; 78let mediumCount = 0; 79let lowCount = 0; 80let allCount = 100; 81for (let i: number = 0; i < allCount; i++) { 82 taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { 83 lowCount++; 84 console.log("taskpool lowCount is :" + lowCount); 85 }); 86 taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { 87 mediumCount++; 88 console.log("taskpool mediumCount is :" + mediumCount); 89 }); 90 taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { 91 highCount++; 92 console.log("taskpool highCount is :" + highCount); 93 }); 94} 95``` 96 97**References** 98 99[Priority](../reference/apis/js-apis-taskpool.md) 100 101## How do I convert the implementation in the Java-like thread model (memory sharing) to the implementation in the ArkTS thread model (memory isolation)? (API version 10) 102 103Use **TaskPool** APIs for conversion in the following scenarios: 104 105Scenario 1: Execute independent time-consuming tasks in a subthread, rather than the main thread. 106 107Sample code for memory sharing 108 109```ts 110class Task { 111 static run(args) { 112 // Do some independent task 113 } 114} 115 116let thread = new Thread(() => { 117 let result = Task.run(args) 118 // deal with result 119}) 120``` 121 122ArkTS sample code 123 124```ts 125import taskpool from '@ohos.taskpool' 126@Concurrent 127function run(args: string) { 128 // Do some independent task 129} 130 131let args: string = ''; 132let task = new taskpool.Task(run, args) 133taskpool.execute(task).then((ret: string) => { 134 // Return result 135}) 136``` 137 138Scenario 2: Use the created class instance in a subthread, rather than the main thread. 139 140Sample code for memory sharing 141 142```ts 143class Material { 144 action(args) { 145 // Do some independent task 146 } 147} 148 149let material = new Material() 150let thread = new Thread(() => { 151 let result = material.action(args) 152 // deal with result 153}) 154``` 155 156ArkTS sample code 157 158```ts 159import taskpool from '@ohos.taskpool' 160@Concurrent 161function runner(material: Material, args: string): void { 162 return material.action(args); 163} 164 165class Material { 166 action(args: string) { 167 // Do some independent task 168 } 169} 170 171let material = new Material() 172taskpool.execute(runner, material).then((ret: string) => { 173 // Return result 174}) 175``` 176 177Scenario 3: Execute independent time-consuming tasks in a subthread, rather than the main thread. 178Sample code for memory sharing 179 180```ts 181class Task { 182 run(args) { 183 // Do some independent task 184 task.result = true 185 } 186} 187 188let task = new Task() 189let thread = new Thread(() => { 190 let result = task.run(args) 191 // deal with result 192}) 193``` 194 195ArkTS sample code 196 197```ts 198import taskpool from '@ohos.taskpool' 199@Concurrent 200function runner(task: Task) { 201 let args: string = ''; 202 task.run(args); 203} 204 205class Task { 206 result: string = ''; 207 208 run(args: string) { 209 // Do some independent task 210 return true; 211 } 212} 213 214let task = new Task(); 215taskpool.execute(runner, task).then((ret: string) => { 216 task.result = ret; 217}) 218``` 219 220 221**References** 222 223[Concurrency Overview](../arkts-utils/concurrency-overview.md) 224 225## What are the differences between TaskPool and Worker? What are their recommended scenarios? (API version 10) 226 227**TaskPool** and **Worker** are concurrent APIs of different granularities. **TaskPool** provides APIs at the level of tasks, whereas **Worker** provides APIs at the level of threads or services. 228 229**TaskPool** simplifies concurrent program development, supports priority setting and cancellation, and saves system resources and optimizes scheduling through unified management. 230 231Similarities: In terms of interaction with JS-related threads, both of them feature memory isolation. They pose the same restrictions on parameters and value ranges, and they also have overhead. (Pay attention to the granularity of concurrent tasks.) 232 233**References** 234 235[Comparison Between TaskPool and Worker](../arkts-utils/taskpool-vs-worker.md) 236 237## Do Worker and TaskPool limit the number of threads? What will happen if the maximum number is reached? Will the task pool be affected when the number of worker threads reaches the upper limit? (API version 10) 238 239**TaskPool** dynamically adjusts the number of threads based on hardware conditions and task loads. It does not support setting a number. Tasks are added to the thread pool, and high-priority tasks are executed first. 240 241A maximum of eight worker threads can be created. No more worker threads can be created when the maximum number is reached. 242 243**TaskPool** and **Worker** are independent of each other. 244 245**References** 246 247[Comparison Between TaskPool and Worker](../arkts-utils/taskpool-vs-worker.md) 248 249## Is there a thread-safe container class? (API version 10) 250 251Objects are not directly shared, and therefore all containers are thread-safe. 252 253**References** 254 255[Asynchronous Concurrency Overview (Promise and Async/Await)](../arkts-utils/async-concurrency-overview.md) 256 257## What is the task scheduling mechanism in TaskPool and Worker? Do they provide the same event loop mechanism as the JS single thread? (API version 10) 258 259**TaskPool** and **Worker** use the event loop to receive messages exchanged between threads. 260**Worker** does not support the setting of the message priority, but **TaskPool** does. 261 262## What is the multithreading model of the system? (API version 10) 263 264**TaskPool** APIs are provided to support multithreading development. Resident time-consuming tasks can use worker threads, with the maximum number limited to eight. 265 266It is recommended that the FFRT thread pool be used on the native side. There is no restriction on pthread. 267 268## Can context be transferred across threads? (API version 10) 269 270Yes. Context can be directly transferred as a parameter. 271 272**References** 273 274[Shared Objects](../arkts-utils/serialization-support-types.md) 275 276## How do I implement secure access to the same shared memory in multithreaded concurrency scenarios? (API version 10) 277 278You can use SharedArrayBuffer. If multiple operations are simultaneously performed to modify data stored in an object of the SharedArrayBuffer type, you must use atomic operations to ensure data synchronization. The atomic operations ensure that the current operation is complete before the next operation starts. 279 280**Sample Code** 281 282```ts 283// index.ets 284let sab = new SharedArrayBuffer(32); 285// int32 buffer view for sab 286let i32a = new Int32Array(sab); 287i32a[0] = 0; 288 289let producer = new worker.ThreadWorker("entry/ets/workers/worker_producer.ts"); 290producer.postMessage(sab); 291 292function consumection(e: MessageEvents) { 293 let sab: SharedArrayBuffer = e.data; 294 let i32a = new Int32Array(sab); 295 console.info("Customer: received sab"); 296 while (true) { 297 Atomics.wait(i32a, 0, 0); //blocked here until be waked. 298 let length = i32a.length; 299 for (let i = length - 1; i > 0; i--) { 300 console.info("arraybuffer " + i + " value is " + i32a[i]); 301 i32a[i] = i; 302 } 303 } 304} 305``` 306 307## Which has a higher priority, the main thread or subthread? What are their task execution policies? (API version 10) 308 309As the UI thread, the main thread has the highest priority. When the load is high, a thread with a higher priority is executed faster. When the load is low, the execution pace is similar for threads with different priorities. 310 311Subthreads support priority setting, and the priority affects their scheduling. 312 313## Are there ArkTS APIs for forcibly switching thread execution and scheduling globally? (API version 10) 314 315**Worker** can throw tasks to the parent thread through **PostMessage**. **TaskPool** can send messages to the parent thread to trigger tasks. 316 317**References** 318 3191. [@ohos.taskpool (Using the Task Pool)](../reference/apis/js-apis-taskpool.md) 3202. [@ohos.worker (Worker Startup)](../reference/apis/js-apis-worker.md) 321 322## Does ArkTS support multithreading development using a Java-like shared memory model? (API version 10) 323 324Multiple threads cannot perform operations on the same memory object simultaneously by locking the memory object. ArkTS is an actor model that supports cross-thread memory isolation. Currently, only SharedArrayBuffer or native-layer objects can be shared. 325 326**References** 327 328[Multithreaded Concurrency Overview (TaskPool and Worker)](../arkts-utils/multi-thread-concurrency-overview.md) 329 330 331## Do ArkTS APIs support overloading? How do I implement overloading in them? (API version 10) 332 333ArkTS supports overloading in TS, that is, multiple overload signatures + implementation signature + function bodies. Function signatures are used only for type check during build. They are not retained at runtime. 334 335ArkTS does not support overloading of multiple function bodies. 336 337**Sample Code** 338 339```ts 340class User { 341 age: number 342 343 constructor(age: number) { 344 this.age = age 345 } 346} 347 348// Declaration 349function test(param: User): number; 350 351function test(param: number, flag: boolean): number; 352 353// Implementation 354function test(param: User | number, flag?: boolean) { 355 if (typeof param === 'number') { 356 return param + (flag ? 1 : 0) 357 } else { 358 return param.age 359 } 360} 361``` 362 363## What is the thread mechanism? Is each thread a separate JS engine? If a thread has relatively low overhead, why is the number of threads limited? (API version 10) 364 365A device has a limited number of cores. Too many threads cause high scheduling overhead and memory overhead. 366 367The system provides the ArkTS task pool and FFRT task pool to support unified scheduling. 368 369The JS part of the ArkTS thread is implemented based on the actor model. Each thread has an independent JS environment instance. Therefore, starting a thread consumes a large amount of memory. 370 371In other operating systems, the large number of application threads is caused by the synchronization lock and synchronization I/O programming. 372 373In OpenHarmony, asynchronous I/O calls are distributed to the I/O thread pool and do not block application threads. Therefore, the number of threads required is far less than that in other operating systems. 374 375## How does the task pool communicate with the main thread during task execution? How do I implement simultaneous access to the same memory variable? (API version 10) 376 377Tasks in the task pool can trigger the **onReceiveData** callback of the main thread through **sendData**. 378Multiple threads can use SharedArrayBuffer to operate the memory block. 379 380## Are multithreading operations on the preferences and databases thread safe? (API version 10) 381 382They are thread safe. 383 384## If most background tasks (computing, tracing, and storage) in ArkTS use asynchronous concurrency mode, will the main thread become slower and finally cause frame freezing and frame loss? (API version 10) 385 386If I/O operations are not involved, asynchronous tasks of ArkTS APIs are triggered at the microtask execution time of the main thread and still occupy the main thread. You are advised to use **TaskPool** to distribute the tasks to the background task pool. 387 388## How do I implement synchronous function calls in ArkTS as easily as using **synchronized** in Java methods? (API version 10) 389 390Currently, the use of **synchronized** is not supported. In the future, the AsyncLock synchronization mechanism will be supported, where code blocks to be synchronized can be placed in asynchronous code blocks. 391 392## Will the main thread be blocked if await is used in the main thread of ArkTS? (API version 10) 393 394**Description** 395 396If the following code is executed in the main thread, will the main thread be blocked? 397 398`const response = await reqeust.buildCall().execute<string>();` 399 400**Answer** 401 402It will not block the main thread. await suspends the current asynchronous task and wakes up the task until the conditions are met. The main thread can process other tasks. 403 404## In C/C++ code, how do I directly call ArkTS APIs in the subthread instead of posting messages to the main thread? (API version 10) 405 406Direct calls are not supported yet. 407 408## Is the underlying running environment of ArkTS code self-developed or open-source? Is the same running environment used for React Native code? (API version 10) 409 410- On the in-house ArkCompiler, the bytecode is run. The bytecode is generated after the ArkTS, TS, or JS source code is compiled using the ArkCompiler toolchain. 411- For React Native, the JS source code is run on the V8 engine provided by the system. 412 413## What data type conversion methods are used in ArkTS? Are they consistent with TS? (API version 10) 414 415ArkTS supports as type conversion of TS, but not type conversion using the <> operator. Currently, the as type conversion can be used during build, but not at runtime. 416 417ArkTS also supports built-in type conversion functions, such as **Number()**, **String()**, and **Boolean()**. 418 419**References** 420 421[TypeScript to ArkTS Cookbook](../quick-start/typescript-to-arkts-migration-guide.md) 422 423## Can an application manage the background I/O task pool? Is any open API provided for management? (API version 10) 424 425- The background TaskPool threads are determined by the load and hardware. No open API is provided. However, you can use the serial queue and task group for task management. 426- The I/O task pool is scheduled at the bottom layer and cannot be managed by an application. 427 428## Will the system continue to support .ts file development in the future? (API version 10) 429 430**Description** 431 432Will the basic libraries implemented based on TS be compatible in the future? For example, the .ts file supports **any** and dynamic type conversion at runtime, but the .ets file does not. 433 434**Answer** 435 436The system will continue to support the standard TS syntax and be compatible with the existing third-party libraries implemented on TS. 437 438## Is dynamic module loading supported? How do I implement it? (API version 10) 439 440Currently, the binary package on the device side cannot be dynamically loaded. You can use the dynamic import feature for asynchronous loading. This achieves the effect similar to the reflection API **Class.forName()**. 441 442The following is an example. The HAP dynamically imports **harlibrary** and calls the static member function **staticAdd()**, instance member function **instanceAdd()**, and global method **addHarLibrary()**. 443 444```ts 445/ / src/main/ets/utils/Calc.ets of harlibrary 446export class Calc { 447 public constructor() {} 448 public static staticAdd(a: number, b: number): number { 449 let c = a + b; 450 console.log("DynamicImport I'm harLibrary in staticAdd, %d + %d = %d", a, b, c); 451 return c; 452 } 453 public instanceAdd(a: number, b: number): number { 454 let c = a + b; 455 console.log("DynamicImport I'm harLibrary in instanseAdd, %d + %d = %d", a, b, c); 456 return c; 457 } 458} 459 460export function addHarLibrary(a: number, b: number): number { 461 let c = a + b; 462 console.log("DynamicImport I'm harLibrary in addHarLibrary, %d + %d = %d", a, b, c); 463 return c; 464} 465 466// index.ets of harlibrary 467export { Calc, addHarLibrary } from './src/main/ets/utils/Calc'; 468 469// index.ets of hap 470let harLibrary = 'harlibrary'; 471import(harLibrary).then((ns: ESObject) => { // Dynamic variable import is a new feature. Changing an input parameter to the string 'harlibrary' is supported in earlier versions. You can also use the await import mode. 472 ns.Calc.staticAdd(7, 8); // Call the static member function staticAdd() with reflection. 473 let calc: ESObject = new ns.Calc(); // Instantiate the class Calc. 474 calc.instanceAdd(8, 9); // Call the instance member function instanceAdd(). 475 ns.addHarLibrary(6, 7); // Call the global method addHarLibrary(). 476}); 477``` 478 479 480 481## Multithreading occupies a large amount of memory. Each thread requires an ArkTS engine, which means more memory is occupied. How do I fully utilize the device performance with a limited number of threads? 482 483The ArkTS worker thread creates an ArkTS engine instance, which occupies extra memory. 484 485In addition, ArkTS provides TaskPool concurrent APIs, which are similar to the thread pool of GCD. Tasks can be executed without thread lifecycle management. Tasks are scheduled to a limited number of worker threads for execution. Multiple tasks share these worker threads (ArkTS engine instances). The system scales in or out the number of worker threads based on the load to maximize the hard performance. 486 487To address the problem that a large number of threads are required, you are advised to: 488 4891. Convert multi-thread tasks into concurrent tasks and distribute them through the task pool. 4902. Execute I/O tasks in the calling thread (which can be the TaskPool thread), rather than starting new threads for them. 4913. Use worker threads (no more than 8) for resident CPU intensive tasks (which is of a small number). 492 493**References** 494 495[Comparison Between TaskPool and Worker](../arkts-utils/taskpool-vs-worker.md)