diff --git a/Lib/profiling/sampling/gecko_collector.py b/Lib/profiling/sampling/gecko_collector.py index 28ef9b69bf7968..7b42253e50f636 100644 --- a/Lib/profiling/sampling/gecko_collector.py +++ b/Lib/profiling/sampling/gecko_collector.py @@ -171,13 +171,18 @@ def collect(self, stack_frames, timestamps_us=None): # Process threads for interpreter_info in stack_frames: + # Since 'threads' is in order from newest to oldest, + # we know the first thread must be the main thread. + main_tid = None + if len(interpreter_info.threads) != 0: + main_tid = interpreter_info.threads[-1].thread_id for thread_info in interpreter_info.threads: frames = filter_internal_frames(thread_info.frame_info) tid = thread_info.thread_id # Initialize thread if needed if tid not in self.threads: - self.threads[tid] = self._create_thread(tid) + self.threads[tid] = self._create_thread(tid, main_tid) thread_data = self.threads[tid] @@ -288,14 +293,10 @@ def collect(self, stack_frames, timestamps_us=None): self.sample_count += len(times) - def _create_thread(self, tid): + def _create_thread(self, tid, main_tid): """Create a new thread structure with processed profile format.""" - # Determine if this is the main thread - try: - is_main = tid == threading.main_thread().ident - except (RuntimeError, AttributeError): - is_main = False + is_main = tid == main_tid thread = { "name": f"Thread-{tid}",