Symptom:
The game interface freezes while loading a level; clicking on it causes a "Program Not Responding" pop-up to appear
Cause Analysis:
1. The most likely cause is that level resources are being loaded on the main thread (UI thread), causing the UI to freeze before loading is complete
2. A secondary possible cause is that the main thread is waiting for an extended period for a lock held by the resource loading thread, causing the UI to freeze
Optimization Recommendation 1: Separate Functions
1. Do not load level resources on the main thread; instead, start a new thread to handle the loading.
2. Minimize the use of locks between the main thread and the loading thread. Instead, communicate using atomic variables, channels, or similar structures, and return a smart pointer holding the resources once loading is complete. In other words, “do not communicate via shared memory; instead, use communication to share memory.”
3. For example, the main thread creates a resource loading thread and uses an atomic variable to track the loading progress. The main thread polls this variable and retrieves the loaded resources once the process is complete.
Advantage: Prevents UI freezes during loading
Optimization Recommendation 2: Parallel Loading
1. Given the widespread use of multi-core CPUs and NVMe drives, a multi-threaded parallel loading strategy can significantly reduce level loading times if loading tasks are evenly distributed.
2. If the level loading process involves not only file reading but also time-consuming data processing, asynchronizing the loading process allows file reading and data processing to occur simultaneously, further saving time.
Advantage: Improves loading speed
Optimization Recommendation 3: Distinguish Between Static Resources and State Data; Delay Resource Release
1. Classify game data into static resources that remain unchanged during program execution (such as airport and aircraft models) and dynamically changing states
2. When a level ends, release only the state and do not release the resources yet
3. If the same level is replayed, reuse the original resources directly; if a different level is played, release the original resources
Benefit: Faster loading times when replaying levels
Optimization Recommendation 4: Fine-Grained Categorization of Static Resources
1. Building on Recommendation 3, further subdivide resources, such as airport models and aircraft models
2. When playing a different level, reuse resources shared between the two levels and release unused resources
Advantage: Improves loading speed when playing different levels