Skip to content

Commit 4a82ac9

Browse files
committed
profiling(Gecko): Properly obtain main thread identifier
Since running a profiler via CLI (python -m profiling.sampling run) spawns a new subprocess where the actual user-specified code will run, a call to threading.main_thread() in the collector's process will not return the profiled process's main thread. To combat this, we rely on the fact that thread objects are inserted in such a way that the first object in the list represents the oldest ThreadState object [1], which corresponds to a ThreadState associated with the main thread. [1] - https://github.com/python/cpython/blob/1b118353bb0a9d816de6ef673f3b11775de5bec5/Include/internal/pycore_interp_structs.h#L831 Signed-off-by: Sofia Donato Ferreira <flowlnlnln@gmail.com>
1 parent 2a0fa50 commit 4a82ac9

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Lib/profiling/sampling/gecko_collector.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,14 +170,19 @@ def collect(self, stack_frames, timestamps_us=None):
170170
self.last_sample_time = times[-1]
171171

172172
# Process threads
173+
main_tid = None
173174
for interpreter_info in stack_frames:
174175
for thread_info in interpreter_info.threads:
175176
frames = filter_internal_frames(thread_info.frame_info)
176177
tid = thread_info.thread_id
177178

178179
# Initialize thread if needed
179180
if tid not in self.threads:
180-
self.threads[tid] = self._create_thread(tid)
181+
# Since 'threads' is in order from oldest to newest,
182+
# we know the first thread must be the main thread.
183+
if len(self.threads) == 0:
184+
main_tid = tid
185+
self.threads[tid] = self._create_thread(tid, main_tid)
181186

182187
thread_data = self.threads[tid]
183188

@@ -288,14 +293,10 @@ def collect(self, stack_frames, timestamps_us=None):
288293

289294
self.sample_count += len(times)
290295

291-
def _create_thread(self, tid):
296+
def _create_thread(self, tid, main_tid):
292297
"""Create a new thread structure with processed profile format."""
293298

294-
# Determine if this is the main thread
295-
try:
296-
is_main = tid == threading.main_thread().ident
297-
except (RuntimeError, AttributeError):
298-
is_main = False
299+
is_main = tid == main_tid
299300

300301
thread = {
301302
"name": f"Thread-{tid}",

0 commit comments

Comments
 (0)