Skip to content

Commit 60022d0

Browse files
committed
Expose the main thread ID in the reader
To be able to filter allocations that happened only on the thread that started the tracking, expose the main thread ID in the reader class. Signed-off-by: Pablo Galindo <pablogsal@gmail.com>
1 parent 578e02d commit 60022d0

File tree

5 files changed

+31
-0
lines changed

5 files changed

+31
-0
lines changed

news/560.feature.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Expose the main thread id in the FileReader's metadata attribute.

src/memray/_memray.pyx

+1
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,7 @@ cdef _create_metadata(header, peak_memory):
754754
peak_memory=peak_memory,
755755
command_line=header["command_line"],
756756
pid=header["pid"],
757+
main_thread_tid=header["main_tid"],
757758
python_allocator=allocator_id_to_name[header["python_allocator"]],
758759
has_native_traces=header["native_traces"],
759760
trace_python_allocators=header["trace_python_allocators"],

src/memray/_metadata.py

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ class Metadata:
1111
peak_memory: int
1212
command_line: str
1313
pid: int
14+
main_thread_tid: int
1415
python_allocator: str
1516
has_native_traces: bool
1617
trace_python_allocators: bool

tests/unit/test_reader.py

+26
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import threading
23

34
import pytest
45

@@ -79,3 +80,28 @@ def test_read_pid(tmp_path):
7980

8081
# THEN
8182
assert FileReader(output).metadata.pid == os.getpid()
83+
84+
85+
def test_read_tid(tmp_path):
86+
# GIVEN
87+
output = tmp_path / "test.bin"
88+
allocator = MemoryAllocator()
89+
90+
def func():
91+
allocator.valloc(1024)
92+
93+
# WHEN
94+
t = threading.Thread(target=func)
95+
with Tracker(output):
96+
func()
97+
t.start()
98+
t.join()
99+
100+
# THEN
101+
reader = FileReader(output)
102+
main_tid = reader.metadata.main_thread_tid
103+
all_allocations = reader.get_allocation_records()
104+
all_tids = tuple(allocation.tid for allocation in all_allocations)
105+
assert main_tid in set(all_tids)
106+
# The main thread should be the first one in the list
107+
assert main_tid == all_tids[0]

tests/unit/test_stats_reporter.py

+2
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ def fake_stats():
9797
python_allocator="pymalloc",
9898
has_native_traces=False,
9999
trace_python_allocators=True,
100+
main_thread_tid=0x1,
100101
),
101102
total_num_allocations=20,
102103
total_memory_allocated=sum(mem_allocation_list),
@@ -435,6 +436,7 @@ def test_stats_output_json(fake_stats, tmp_path):
435436
"python_allocator": "pymalloc",
436437
"has_native_traces": False,
437438
"trace_python_allocators": True,
439+
"main_thread_tid": 0x1,
438440
},
439441
}
440442
actual = json.loads(output_file.read_text())

0 commit comments

Comments
 (0)