Overview of Concurrency

Concurrency refers to the situation where multiple tasks are executed at the same time. On a multi-core device, tasks can be executed concurrently on different CPUs. On single-core devices, while multiple tasks are not executed at the same time, the CPU can switch between tasks when one is idle or performing I/O operations, thereby optimizing CPU resource utilization.

To improve the response speed and frame rate of applications and mitigate the impact of time-consuming tasks on the UI main thread, ArkTS provides two concurrency strategies: asynchronous concurrency and multithreaded concurrency.

  • Asynchronous concurrency involves pausing asynchronous code at a certain point and resuming its execution later, ensuring that only one piece of code is running at any given moment. ArkTS supports asynchronous concurrency through Promises and async/await, which are well-suited for scenarios involving single I/O operations. For details, see Asynchronous Concurrency.

  • Multithreaded concurrency allows multiple code segments to be executed concurrently. While the UI main thread continues to handle user interactions and update the UI, background threads can perform time-consuming operations, thereby preventing application lag. ArkTS supports multithreaded concurrency through TaskPool and Worker, which are ideal for scenarios involving time-consuming tasks. For details, see Multithreaded Concurrency.

In multithreaded concurrency scenarios, data communication between different threads is necessary. Different types of objects may use different transfer methods, such as copy or memory sharing.

Concurrency capabilities are used in various scenarios, including asynchronous tasks, time-consuming tasks (CPU intensive tasks, I/O intensive tasks, and synchronous tasks), continuous tasks, and resident tasks. You can select the appropriate concurrency strategy based on the specific task requirements and scenarios for optimization and development. You can also refer to Multithreaded Development Practice Cases.