Skip to content

Instantly share code, notes, and snippets.

@egolearner
Created August 27, 2025 02:36
Show Gist options
  • Select an option

  • Save egolearner/55392807b253599b1af8617744f217cd to your computer and use it in GitHub Desktop.

Select an option

Save egolearner/55392807b253599b1af8617744f217cd to your computer and use it in GitHub Desktop.
import re
from collections import defaultdict
import sys
def parse_thread_stacks(input_text):
"""
Parse the input text to extract thread IDs and their corresponding stacks.
"""
threads = {}
current_tid = None
current_stack = []
for line in input_text.splitlines():
line = line.strip()
# Match TID line
#tid_match = re.match(r'^TID (\d+):$', line)
#tid_match = re.match(r'^Thread (\d+).*:$', line)
tid_match = re.match(r'^(Thread|TID) (\d+).*:$', line)
if tid_match:
if current_tid is not None and current_stack:
# Store the previous thread's stack
threads[current_tid] = current_stack
current_tid = int(tid_match.group(2))
current_stack = []
# Match stack frame line
elif line.startswith("#"):
current_stack.append(line)
# Add the last thread's stack
if current_tid is not None and current_stack:
threads[current_tid] = current_stack
return threads
def group_threads_by_stack(threads):
"""
Group threads by their stack traces.
"""
stack_groups = defaultdict(list)
for tid, stack in threads.items():
stack_tuple = tuple(stack) # Use tuple because lists are not hashable
stack_groups[stack_tuple].append(tid)
return stack_groups
def main():
# Read input from standard input
input_text = sys.stdin.read()
# Parse and group threads
threads = parse_thread_stacks(input_text)
stack_groups = group_threads_by_stack(threads)
# Output grouped threads and their stacks
for stack, tids in stack_groups.items():
if len(tids) >= 1: # Only print groups with more than one TID
print(f"Threads: {', '.join(map(str, tids))}")
print("Stack:")
for frame in stack:
print(frame)
print() # Blank line between groups
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment