ThreadRace README

项目的 README,来自 github.com/AhmadHassan-BTed/ThreadRace。合并为一个 markdown 文件:README.md。

ThreadRace

A C++ Concurrency Telemetry Framework & Execution Speed Tester

License: MIT C++11 Build

Time is a non-renewable, precious human resource. ThreadRace is designed to measure, analyze, and visualize the performance differential between sequential and parallel execution paradigms.

Philosophy • Demonstration • Architecture • Workflow • Repository Structure • Build & Run • Contributing


Philosophy

In daily human life, tasks are split and executed simultaneously to conserve time-cooking while listening to audio, or thinking about future plans while walking. ThreadRace is an engineering reflection of this fundamental human urge: the quest for concurrency.

By comparing Typical (Sequential) execution with Threaded (Parallel) execution, ThreadRace measures the efficiency of digital cooperation. The Ackermann Function-a deeply recursive mathematical operation-is utilized as a benchmark task to represent high-complexity, processor-intensive operations that demand efficient thread synchronization and compute optimization.


Visual Showcase & Demonstration

ThreadRace provides high-precision CLI timing telemetry alongside a 60 FPS Native C++ SDL2 + OpenGL Hardware-Accelerated Visualizer Suite (bin/ackermann_visualizer).

Visualizer Suite Modes

Mode 1: Quantum Branching Network (2D/3D Force Tree)
Quantum Branching Network Mode

Displays the dynamic recursive execution tree with glowing OpenGL nodes, Bezier branch curves, starburst particles on base-case evaluations, and real-time camera tracking.


Mode 2: Hyper-Logarithmic 3D Landscape (OpenGL Terrain Height Map)
Hyper-Logarithmic 3D Landscape Mode

Visualizes Ackermann growth $A(m, n)$ on a 3D height field terrain log-compressed using $Z(m, n) = \ln(1 + \ln(1 + A(m, n)))$.


Mode 3: Golden Spiral Phase Orbit
Golden Spiral Phase Orbit Mode

Maps call stack depth and frame steps onto a logarithmic golden ratio $\phi$ particle galaxy with glowing orbit trails and depth rings.


Mode 4: Head-to-Head Thread Race Arena
Head-to-Head Thread Race Arena Mode

Direct side-by-side competition comparing Sequential (1 Thread) vs. Parallel Execution, showing active threads, memory footprint, speedup telemetry, step progress bars, and finish line detection.


Execution Benchmark CLI Outputs

Regular Execution Benchmark Output
Regular Execution Speed (Typical vs Threaded)

Ackermann Function Benchmark Telemetry (m=4, n=1)
Sequential Ackermann Run Threaded Ackermann Run


Native C++ Ackermann Visualizer Suite

The native visualizer suite (bin/ackermann_visualizer) bridges pure math, real-time audio synthesis, OpenGL graphic rendering, and threading telemetry into an immersive interactive application.

Key Features:

Build & Run Native C++ Visualizer:

make all
./bin/ackermann_visualizer [m] [n]

Keyboard & Mouse Controls:


Architecture Overview

The codebase uses clean object-oriented patterns isolating telemetry capture, computational task definitions, execution strategies, and visual rendering modules.

Static Structure (Class Relationships)

classDiagram
    class ITask {
        <<interface>>
        +execute()*
        +getName()* string
    }

    class IExecutionStrategy {
        <<interface>>
        +run(ITask, iterations)*
        +getStrategyName()* string
    }

    class AckermannTask {
        -int m
        -int n
        +execute()
        +getName() string
        -ackermann(m, n) int
    }

    class SequentialStrategy {
        +run(ITask, iterations)
    }

    class ThreadedStrategy {
        +run(ITask, iterations)
    }

    class Benchmarker {
        -IExecutionStrategy strategy
        +runBenchmark(ITask, iterations)
    }

    class AckermannStackEngine {
        -int m
        -int n
        +step()
        +getNodes()
        +getMetrics()
        +setEventCallback()
    }

    class RaceEngine {
        -int m
        -int n
        -int parallelWorkers
        +step(stepDelayMs, isPlaying)
        +getSequentialTelemetry()
        +getParallelTelemetry()
    }

    class AudioSynthesizer {
        +init()
        +playNote(depth, isResolve)
        +playComplete()
    }

    class QuantumTreeRenderer {
        +render(engine, camera)
        +spawnStarburst(x, y, r, g, b)
    }

    class Landscape3DRenderer {
        +render(m, n, camera)
    }

    class SpiralOrbitRenderer {
        +render(engine, camera)
    }

    class RaceArenaRenderer {
        +render(raceEngine, fontRenderer)
    }

    ITask <|-- AckermannTask : implements
    IExecutionStrategy <|-- SequentialStrategy : implements
    IExecutionStrategy <|-- ThreadedStrategy : implements
    Benchmarker --> IExecutionStrategy : uses
    IExecutionStrategy ..> ITask : executes
    RaceEngine --> AckermannStackEngine : uses
    QuantumTreeRenderer ..> AckermannStackEngine : renders
    Landscape3DRenderer ..> AckermannStackEngine : renders
    SpiralOrbitRenderer ..> AckermannStackEngine : renders
    RaceArenaRenderer ..> RaceEngine : renders
    AckermannStackEngine ..> AudioSynthesizer : triggers audio events

Internal Module Structure

%%{init: {'flowchart': {'curve': 'ortho'}}}%%
flowchart TD
    subgraph CoreAbstractions ["Core Abstractions & Drivers"]
        ITask["ITask Interface"]
        IExecutionStrategy["IExecutionStrategy Interface"]
        Benchmarker["Benchmarker Telemetry"]
        Main["main.cpp (time_tester)"]
    end

    subgraph StrategiesAndTasks ["Strategies & Benchmark Tasks"]
        AckermannTask["AckermannTask"]
        SequentialStrategy["SequentialStrategy"]
        ThreadedStrategy["ThreadedStrategy"]
    end

    subgraph VisualizerSuite ["Native C++ OpenGL/SDL2 Visualizer Suite"]
        VisMain["visualizer_main.cpp (ackermann_visualizer)"]
        StackEngine["AckermannStackEngine"]
        RaceEngine["RaceEngine"]
        AudioSynth["AudioSynthesizer (SDL Audio Callback)"]
        FontRenderer["FontRenderer (Bitmap Text HUD)"]
        
        TreeRender["QuantumTreeRenderer (Mode 1)"]
        LandRender["Landscape3DRenderer (Mode 2)"]
        OrbitRender["SpiralOrbitRenderer (Mode 3)"]
        ArenaRender["RaceArenaRenderer (Mode 4)"]
    end

    AckermannTask -.-> ITask
    SequentialStrategy -.-> IExecutionStrategy
    ThreadedStrategy -.-> IExecutionStrategy
    Benchmarker --> IExecutionStrategy
    Main --> Benchmarker

    VisMain --> StackEngine
    VisMain --> RaceEngine
    VisMain --> AudioSynth
    VisMain --> FontRenderer
    VisMain --> TreeRender
    VisMain --> LandRender
    VisMain --> OrbitRender
    VisMain --> ArenaRender

System Workflow & Request Lifecycle

When a run is initiated via the command line, the execution flows through parsing, strategy instantiation, timed processing, and telemetry reporting.

sequenceDiagram
    participant User as Terminal CLI
    participant Main as main.cpp
    participant Bench as Benchmarker
    participant Strategy as IExecutionStrategy
    participant Task as ITask

    User->>Main: Execute program with mode & iterations
    Main->>Strategy: Instantiate (Sequential or Threaded)
    Main->>Task: Instantiate AckermannTask(4, 1)
    Main->>Bench: Instantiate with selected Strategy
    Main->>Bench: runBenchmark(Task, iterations)

    rect rgb(28, 30, 36)
        Note over Bench, Task: Telemetry Capture Span
        Bench->>Bench: Start high_resolution_clock timer
        Bench->>Strategy: run(Task, iterations)

        loop For each Iteration
            Strategy->>Task: execute()
            Task->>Task: Compute Ackermann value
            Task-->>Strategy: Return Result (65533)
        end

        Strategy-->>Bench: Return Control
        Bench->>Bench: Stop high_resolution_clock timer
    end

    Bench-->>User: Output timings (Real, User, System, CPU%)

Concurrency and Telemetry Specifications


Data & Request Lifecycle Flow

The parameters and runtime performance data flow through the framework as detailed below:

%%{init: {'flowchart': {'curve': 'ortho'}}}%%
flowchart LR
    Args[CLI Arguments] --> Parse[main.cpp Parse]
    Parse -->|Config Object| Strategy[Strategy Config]
    Parse -->|Parameters| Task[Task Config]

    subgraph TelemetryContext ["Telemetry & Performance Evaluation"]
        Strategy --> RunStrategy[Execute Strategy::run]
        Task --> RunStrategy

        RunStrategy --> Timer[Start Chrono Clock]
        Timer --> CoreComputation[Task::execute Iterations]
        CoreComputation --> TimerStop[Stop Chrono Clock]
    end

    TimerStop --> Metrics[Compute Telemetry Metrics]
    Metrics --> Terminal[Format & Output Terminal Report]

Repository Structure

The physical layout isolates public include headers, logic implementations, graphics assets, and compiled targets:

ThreadRace/
├── .editorconfig
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── assets/
│   ├── Visualization1.png    # Mode 1: Quantum Tree Screenshot
│   ├── Visualization2.png    # Mode 2: 3D Landscape Screenshot
│   ├── Visualization3.png    # Mode 3: Spiral Orbit Screenshot
│   ├── Visualization4.png    # Mode 4: Thread Race Arena Screenshot
│   ├── ack-1.png             # Sequential Ackermann CLI Output
│   ├── ack-2.png             # Threaded Ackermann CLI Output
│   └── reg.png               # Regular Benchmark CLI Output
├── docs/
│   ├── architecture.md       # High-Level Design & Visualizer System Architecture
│   └── development.md        # Build Instructions & Test Protocols
├── include/
│   ├── Benchmarker.hpp
│   ├── core/
│   │   ├── IExecutionStrategy.hpp
│   │   └── ITask.hpp
│   ├── strategies/
│   │   ├── SequentialStrategy.hpp
│   │   └── ThreadedStrategy.hpp
│   ├── tasks/
│   │   └── AckermannTask.hpp
│   └── visualizer/
│       ├── AckermannStackEngine.hpp
│       ├── AudioSynthesizer.hpp
│       ├── FontRenderer.hpp
│       ├── Landscape3DRenderer.hpp
│       ├── QuantumTreeRenderer.hpp
│       ├── RaceArenaRenderer.hpp
│       ├── RaceEngine.hpp
│       └── SpiralOrbitRenderer.hpp
├── bin/                      # Compiled Executables (time_tester, ackermann_visualizer)
├── obj/                      # Compiled Object Files
└── src/
    ├── Benchmarker.cpp
    ├── main.cpp
    ├── strategies/
    │   ├── SequentialStrategy.cpp
    │   └── ThreadedStrategy.cpp
    ├── tasks/
    │   └── AckermannTask.cpp
    └── visualizer/
        ├── AckermannStackEngine.cpp
        ├── AudioSynthesizer.cpp
        ├── FontRenderer.cpp
        ├── Landscape3DRenderer.cpp
        ├── QuantumTreeRenderer.cpp
        ├── RaceArenaRenderer.cpp
        ├── RaceEngine.cpp
        ├── SpiralOrbitRenderer.cpp
        └── visualizer_main.cpp

Build & Execution Pipeline

The compilation process is managed by a POSIX-compliant Makefile, compiling C++ files with production optimizations (-O2).

%%{init: {'flowchart': {'curve': 'ortho'}}}%%
flowchart TD
    SrcMain["src/main.cpp"] -->|g++ -c| ObjMain["obj/main.o"]
    SrcBench["src/Benchmarker.cpp"] -->|g++ -c| ObjBench["obj/Benchmarker.o"]
    SrcStrat["src/strategies/*.cpp"] -->|g++ -c| ObjStrat["obj/*.o"]
    SrcTasks["src/tasks/*.cpp"] -->|g++ -c| ObjTasks["obj/*.o"]

    ObjMain -->|g++ Linker| Bin["bin/time_tester"]
    ObjBench -->|g++ Linker| Bin
    ObjStrat -->|g++ Linker| Bin
    ObjTasks -->|g++ Linker| Bin

Compilation

Compile the source code using the provided Makefile:

make all

Running Benchmarks

Run the binary with execution strategy modes and iteration count:

Command Execution Model Description
./bin/time_tester 1 Sequential (Typical) Tasks run sequentially in a single execution thread.
./bin/time_tester 2 Parallel (Threaded) Tasks run concurrently across multiple threads.

Custom iterations can be appended as a trailing argument (defaults to 3):

# Execute threaded strategy with 5 iterations
./bin/time_tester 2 5

Development Workflow

Contributors are welcome to submit improvements or add new performance benchmarks. The following pipeline ensures stability:

1. Functional Verification

Ensure the core Ackermann output calculation remains functional and math-accurate:

  • Ackermann(4, 1) must return 65533.
2. Concurrency Stress Testing

Verify stability under threaded loads:

  • Execute mode 2 with a high number of iterations to test against thread leaks or runtime race conditions.
3. CI/CD Integration

On every push or pull request to the main branch, a GitHub Action is triggered to:

  • Configure a clean Ubuntu runner.
  • Validate system compilation with make.
  • Execute regression benchmarks with make test.

Credits & Dedication

ThreadRace was created and engineered by Ahmad Hassan (B-Ted).
Dedicated to the beauty and clarity of highly efficient, low-overhead systems.

ThreadRace (AhmadHassan-BTed/ThreadRace)

正在搜索数据库…

这是什么?ThreadRace 是一个 C++ 框架,以递归的 Ackermann 函数作为工作负载,用于测量并可视化并行(多线程)执行相比顺序执行快了多少。
这只是一个命令行基准测试工具,还是也有图形界面?两者都有:它包含一个命令行计时工具,以及一个独立的原生 C++ 可视化程序(bin/ackermannvisualizer),后者使用 SDL2 和 OpenGL 实时渲染递归过程和线程竞赛。
我该如何构建和运行它?使用所提供的 POSIX Makefile 进行编译,然后带上执行模式参数运行生成的可执行文件,例如顺序执行用 './bin/timetester 1',并行执行用 './bin/timetester 2',还可以选择性地附加迭代次数参数。
要构建和运行可视化程序,需要安装哪些东西?核心基准测试只需要支持 C++11 的编译器(用到 std::thread、std::chrono 和智能指针),而独立的可视化套件还额外需要 SDL2 和 OpenGL 来完成渲染和音频功能。
这个基准测试能反映真实场景的工作负载吗,还是更偏向压力测试?它以 Ackermann 函数为核心,这是一个深度递归的合成函数,之所以选它,是为了考验线程同步和计算优化,而不是为了代表典型的应用程序工作负载。
这个项目是否只在 Linux 上构建和测试过?构建使用符合 POSIX 标准的 Makefile,CI 流水线在 Ubuntu 运行器上编译并测试它;文档中没有提到对 Windows 或 macOS 的支持。
可视化程序的四种模式分别展示什么?模式 1 绘制递归调用栈的 2D/3D 力导向树;模式 2 将 Ackermann 的增长渲染为 3D 对数压缩地形;模式 3 将调用深度映射到黄金分割螺旋轨道上;模式 4 是顺序执行与并行执行并排对比的竞赛场,并附带实时加速比数据。
运行时会发出声音吗?会的,可视化程序具有多声部音频音效化功能,随着递归栈的压入与解开,实时合成 C 大调五声音阶音符,按 M 键即可开关。
如何验证基准测试的正确性?项目的功能验证检查要求 Ackermann(4, 1) 的返回值必须精确等于 65533,并且 GitHub Action 会在每次推送到 main 分支或提交拉取请求时运行这项回归检查。
大小
3.1 MB
星标
4.7K
更新
提交Aug 07
时长
2年
提交 · 90 天