@@ -168,6 +168,7 @@ void DeleteIO(io_object_t value) {
168168 }
169169
170170 double total_cpu_usage = 0.0 ;
171+ uint32_t num_threads = mach_threads.thread_count ;
171172
172173 // Add the CPU usage for each thread. It should be noted that there may be some CPU usage missing
173174 // from this calculation. If a thread ends between calls to this routine, then its info will be
@@ -182,17 +183,30 @@ void DeleteIO(io_object_t value) {
182183 kernel_return_code =
183184 thread_info (mach_threads.threads [i], THREAD_BASIC_INFO,
184185 reinterpret_cast <thread_info_t >(&basic_thread_info), &thread_info_count);
185- if (kernel_return_code != KERN_SUCCESS) {
186- FML_LOG (ERROR) << " Error retrieving thread information: "
187- << mach_error_string (kernel_return_code);
188- return std::nullopt ;
186+ switch (kernel_return_code) {
187+ case KERN_SUCCESS: {
188+ const double current_thread_cpu_usage =
189+ basic_thread_info.cpu_usage / static_cast <float >(TH_USAGE_SCALE);
190+ total_cpu_usage += current_thread_cpu_usage;
191+ break ;
192+ }
193+ case MACH_SEND_TIMEOUT:
194+ case MACH_SEND_TIMED_OUT:
195+ case MACH_SEND_INVALID_DEST:
196+ // Ignore as this thread been destroyed. The possible return codes are not really well
197+ // documented. This handling is inspired from the following sources:
198+ // - https://opensource.apple.com/source/xnu/xnu-4903.221.2/tests/task_inspect.c.auto.html
199+ // - https://github.com/apple/swift-corelibs-libdispatch/blob/main/src/queue.c#L6617
200+ num_threads--;
201+ break ;
202+ default :
203+ FML_LOG (ERROR) << " Error retrieving thread information: "
204+ << mach_error_string (kernel_return_code);
205+ return std::nullopt ;
189206 }
190- const double current_thread_cpu_usage =
191- basic_thread_info.cpu_usage / static_cast <float >(TH_USAGE_SCALE);
192- total_cpu_usage += current_thread_cpu_usage;
193207 }
194208
195- flutter::CpuUsageInfo cpu_usage_info = {.num_threads = mach_threads. thread_count ,
209+ flutter::CpuUsageInfo cpu_usage_info = {.num_threads = num_threads ,
196210 .total_cpu_usage = total_cpu_usage * 100.0 };
197211 return cpu_usage_info;
198212}
0 commit comments