Sunday, December 6, 2026

Revisiting college-days' Maths - there is an uncanny pleasure in it - Studying Vector Calculus once again...


When I was a student of Electronics & TeleComm, Maths was a very rigorous subject. Vector Calculus was a major portion of that Maths syllabus.

But at that time, i was not able to join the dots between different subjects.

I learned the how and what - but not the why.

It was like all different, disconnected knowledge bases... of no use whatsoever at that time.

But after many years in the software industry, when today I am again revisiting Engineering Maths, I am feeling an uncanny pleasure - because now my vision has become broad - and with software expertise - I can visualize what I once studied with a pen and paper.

I solved Maths problems during engineering- with one aim, of course, to do well in the examination.

But today I am learning Vector Calculus just for the joy of relearning.

I have started with the gradient of Vector Calculus and have plans to study Divergence and Curl to start with. 

For this exploration, I chose Julia, a programming language particularly interesting for scientific computing and numerical simulation.

With packages such as Symbolics and GLMakie, we can combine symbolic mathematics with numerical computation and interactive visualisation.

The idea is simple:

  • Define a scalar mathematical function.

  • Calculate its symbolic gradient.

  • Evaluate the gradient numerically at selected points.

  • Calculate its magnitude and unit direction.

  • Visualise the vector field in three-dimensional space.

  • Experiment with different functions and observe the results.

Consider a simple function:

$$f(x,y,z) = x^2 + y^2 + z^2$$

Its gradient is:

$$\nabla f = 2x\hat{i} + 2y\hat{j} + 2z\hat{k}$$

At the point ((1,2,0)), the gradient becomes:

$$\nabla f(1,2,0) = 2\hat{i} + 4\hat{j} + 0\hat{k}$$

Its magnitude is:

$$|\nabla f| = \sqrt{2^2 + 4^2 + 0} = \sqrt{20}$$

Unit direction is:

[0.4472135954999579, 0.8944271909999159, 0.0]

The gradient points radially outward from the origin.

This is where the experience becomes exciting. We are no longer looking at a static diagram in a textbook. We are looking at a mathematical concept unfolding in space.

What makes this exercise particularly interesting is that the same approach can be extended to many engineering subjects.

We can revisit:

  • Vector calculus: gradient, divergence, and curl.

  • Electromagnetics: electric and magnetic fields, field lines, and wave propagation.

  • Circuit theory: transient response of RLC circuits and resonance.

  • Control systems: PID controllers and dynamic system response.

  • Mechanical engineering: vibration, spring-mass-damper systems, and numerical simulation.

  • Heat transfer: temperature distributions and heat diffusion.

These are not merely programming exercises. They are opportunities to build small virtual laboratories where mathematical models, numerical methods, and visual representations come together.

Source code...



using Symbolics
using LinearAlgebra
using GLMakie
using GeometryBasics: Point2f, Vec2f, Point3f, Vec3f

# -----------------------------------------
# 1. Symbolic variables
# -----------------------------------------

@variables x y z

variables = [x, y, z]

# -----------------------------------------
# 2. Allowed mathematical operations
# -----------------------------------------

const ALLOWED_OPERATORS = Set([
    :+, :-, :*, :/, :^
])

const ALLOWED_FUNCTIONS = Dict{Symbol, Function}(
    :sin  => sin,
    :cos  => cos,
    :tan  => tan,
    :exp  => exp,
    :log  => log,
    :sqrt => sqrt,
    :abs  => abs,
)

# -----------------------------------------
# 3. Safely parse mathematical expressions
# -----------------------------------------

function parse_math(ex)

    # Numeric constants
    if ex isa Number
        return ex
    end

    # Variables and constants
    if ex isa Symbol
        if ex == :x
            return x
        elseif ex == :y
            return y
        elseif ex == :z
            return z
        elseif ex == :pi
            return pi
        else
            error("Unknown variable or constant: $ex")
        end
    end

    # Mathematical expressions
    if ex isa Expr && ex.head == :call

        operation = ex.args[1]
        arguments = [parse_math(a) for a in ex.args[2:end]]

        if operation == :+
            return +(arguments...)

        elseif operation == :-
            return -(arguments...)

        elseif operation == :*
            return *(arguments...)

        elseif operation == :/
            return /(arguments...)

        elseif operation == :^
            return arguments[1]^arguments[2]

        elseif operation == :sin
            return sin(arguments...)

        elseif operation == :cos
            return cos(arguments...)

        elseif operation == :tan
            return tan(arguments...)

        elseif operation == :exp
            return exp(arguments...)

        elseif operation == :log
            return log(arguments...)

        elseif operation == :sqrt
            return sqrt(arguments...)

        elseif operation == :abs
            return abs(arguments...)

        else
            error("Unsupported operation: $operation")
        end
    end

    error("Invalid mathematical expression")
end

# -----------------------------------------
# 4. Evaluate symbolic expression at a point
# -----------------------------------------

const NUMERIC_FUNCTION_CACHE = Dict{Any, Any}()

function evaluate_at(expr, point)

    substitutions = Dict(
        x => point[1],
        y => point[2],
        z => point[3]
    )

    numerical_expression = Symbolics.substitute(
        expr,
        substitutions
    )

    return Float64(Symbolics.value(numerical_expression))
end

# -----------------------------------------
# 5. Main gradient calculator
# -----------------------------------------

function calculate_gradient(expression, point)

    parsed_expression = parse_math(
        Meta.parse(expression)
    )

    # Symbolic gradient
    gradient_expression = Symbolics.gradient(
        parsed_expression,
        variables
    )

    # Numerical gradient at selected point
    gradient_value = [
        evaluate_at(component, point)
        for component in gradient_expression
    ]

    # Scalar function value
    function_value = evaluate_at(
        parsed_expression, point
    )

    # Gradient magnitude
    magnitude = norm(gradient_value)

    # Unit direction
    direction = magnitude > 0 ?
        gradient_value / magnitude :
        zeros(3)

    return (
        expression = parsed_expression,
        gradient = gradient_expression,
        function_value = function_value,
        gradient_value = gradient_value,
        magnitude = magnitude,
        direction = direction
    )
end

# -----------------------------------------
# 6. Visualize scalar and gradient fields
# -----------------------------------------

function visualize_gradient(result, point;
                            xrange = (-5.0, 5.0),
                            yrange = (-5.0, 5.0),
                            resolution = 35,
                            arrow_stride = 4)

    # Create coordinate grids
    xs = collect(range(xrange..., length=resolution))
    ys = collect(range(yrange..., length=resolution))

    # Keep z fixed at the user's evaluation coordinate
    z0 = point[3]

    # Calculate scalar field values
    F = [
        try
            evaluate_at(result.expression, [xx, yy, z0])
        catch
            NaN
        end
        for xx in xs, yy in ys
    ]

    # Prepare gradient arrows
    positions = Point2f[]
    directions = Vec2f[]

    for i in 1:arrow_stride:resolution
        for j in 1:arrow_stride:resolution

            xx = xs[i]
            yy = ys[j]

            try
                gx = evaluate_at(
                    result.gradient[1], [xx, yy, z0]
                )

                gy = evaluate_at(
                    result.gradient[2], [xx, yy, z0]
                )

                magnitude = hypot(gx, gy)

                if isfinite(magnitude) && magnitude > 1e-10
                    push!(positions, Point2f(xx, yy))

                    # Normalize arrows to show direction clearly
                    push!(
                        directions,
                        Vec2f(gx / magnitude, gy / magnitude)
                    )
                end
            catch
                continue
            end
        end
    end

    # Create visualization
    fig = Figure(size = (950, 700))

    ax = Axis(
        fig[1, 1],
        xlabel = "x",
        ylabel = "y",
        title = "Scalar Field and Gradient Vector Field",
        aspect = DataAspect()
    )

    # Scalar field: filled contours
    field_plot = contourf!(
        ax, xs, ys, F,
        levels = 25
    )

    Colorbar(
        fig[1, 2],
        field_plot,
        label = "f(x, y, z)"
    )

    # Gradient field: arrows
    arrows!(
        ax,
        positions,
        directions,
        color = :white,
        arrowsize = 12,
        linewidth = 2,
        lengthscale = 0.4
    )

    # Mark the selected evaluation point
    scatter!(
        ax,
        [Point2f(point[1], point[2])],
        color = :red,
        markersize = 14
    )

    display(fig)

    return fig
end

# -----------------------------------------
# 7. 3D Gradient Vector Field Visualization
# -----------------------------------------

function visualize_gradient_3d(result, point;
                                limits = (-3.0, 3.0),
                                resolution = 7)

    # Create a 3D coordinate grid
    coordinates = collect(
        range(limits[1], limits[2], length=resolution)
    )

    positions = Point3f[]
    directions = Vec3f[]
    scalar_values = Float64[]

    # Evaluate the gradient at every grid point
    for xx in coordinates
        for yy in coordinates
            for zz in coordinates

                p = [xx, yy, zz]

                try
                    gx = evaluate_at(result.gradient[1], p)
                    gy = evaluate_at(result.gradient[2], p)
                    gz = evaluate_at(result.gradient[3], p)

                    magnitude = sqrt(gx^2 + gy^2 + gz^2)

                    # Skip zero or invalid vectors
                    if !isfinite(magnitude) || magnitude < 1e-8
                        continue
                    end

                    fvalue = evaluate_at(result.expression, p)

                    if !isfinite(fvalue)
                        continue
                    end

                    push!(positions, Point3f(xx, yy, zz))

                    # Normalize the gradient vectors
                    push!(
                        directions,
                        Vec3f(
                            gx / magnitude,
                            gy / magnitude,
                            gz / magnitude
                        )
                    )

                    push!(scalar_values, fvalue)

                catch
                    continue
                end
            end
        end
    end

    # Create 3D figure
    fig = Figure(size = (1000, 800))

    ax = Axis3(
        fig[1, 1],
        xlabel = "X",
        ylabel = "Y",
        zlabel = "Z",
        title = "3D Gradient Vector Field"
    )

    # Draw gradient arrows
    arrow_plot = arrows!(
        ax,
        positions,
        directions,
        color = scalar_values,
        colormap = :viridis,
        colorrange = extrema(scalar_values),
        lengthscale = 0.45
    )

    Colorbar(
        fig[1, 2],
        arrow_plot,
        label = "Scalar field f(x,y,z)"
    )

    # Mark the selected evaluation point
    scatter!(
        ax,
        [Point3f(point...)],
        color = :red,
        markersize = 18
    )

    display(fig)

    return fig
end

# -----------------------------------------
# 8. Interactive application
# -----------------------------------------

function run_gradient_lab()

    println("\n===================================")
    println("       JULIA VECTOR CALCULUS LAB")
    println("          GRADIENT CALCULATOR")
    println("===================================\n")

    println("Enter a function of x, y, z.")
    println("Example: x^2 + y^2 + z^2")
    println("Type 'exit' to quit.\n")

    while true

        print("Enter function f(x,y,z): ")
        expression = strip(readline())

        lowercase(expression) == "exit" && break

        try
            println("\nEnter evaluation coordinates:")

            print("x = ")
            px = parse(Float64, readline())

            print("y = ")
            py = parse(Float64, readline())

            print("z = ")
            pz = parse(Float64, readline())

            point = [px, py, pz]

            result = calculate_gradient(
                expression, point
            )

            println("\n---------- RESULTS ----------")

            println("\nScalar function:")
            println("f(x,y,z) = ", result.expression)

            println("\nSymbolic gradient:")
            println("∇f = ", result.gradient)

            println("\nEvaluation point:")
            println(point)

            println("\nFunction value:")
            println(result.function_value)

            println("\nNumerical gradient:")
            println(result.gradient_value)

            println("\nGradient magnitude:")
            println(result.magnitude)

            println("\nUnit direction:")
            println(result.direction)

            println("\nGenerating visualization...")

            visualize_gradient(result, point)

            # Uncomment the line below to display the 3D vector field:
            # visualize_gradient_3d(result, point)

            println("\n-----------------------------\n")

        catch error_message
            println("\nError: ", error_message)
            println("Please enter a valid mathematical expression.\n")
        end
    end

    println("\nThank you for using Vector Calculus Lab!")
end

# Start application
run_gradient_lab()

Wednesday, December 2, 2026

Beyond Code. Beyond Classrooms.Towards a New Era of Engineering Education in Bharat. Making Engineering Fun with Julia: An Interactive RLC Circuit Simulator...

Electrical / Electronics engineering becomes much more interesting when we can see equations come alive.

Recently, I developed an interactive Series RLC Circuit Transient Simulator using Julia and GLMakie. The application allows us to change resistance, inductance, and capacitance through sliders and observe how these parameters influence the circuit's transient response.

The project combines circuit theory, numerical methods, and interactive visualization in a single application.

Watch...



The Mathematics Behind the Circuit

A series RLC circuit consists of a resistor, an inductor, and a capacitor connected in series. When a DC step voltage is applied, the circuit current and capacitor voltage evolve over time.

Using Kirchhoff's Voltage Law:

$$ V_s = Ri + L\frac{di}{dt} + V_c $$

The capacitor relationship is:

$$ i = C\frac{dV_c}{dt} $$

These equations can be expressed as a system of first-order differential equations:

$$ \frac{di}{dt} = \frac{V_s - Ri - V_c}{L} $$ $$ \frac{dV_c}{dt} = \frac{i}{C} $$

The simulator uses these equations to calculate the circuit's behavior at every time step.

Enter Runge–Kutta: Solving Differential Equations Numerically

Many engineering systems are described by differential equations that are difficult or inconvenient to solve analytically. Numerical methods provide a way to approximate their solutions.

This project uses the fourth-order Runge–Kutta method (RK4).

The simplest numerical method, Euler's method, estimates the next value using the slope at the beginning of a time interval. RK4 improves this estimate by evaluating the slope four times:

  • (k_1): slope at the beginning of the interval

  • (k_2): slope at the midpoint, using the first estimate

  • (k_3): another midpoint estimate

  • (k_4): slope at the end of the interval

The weighted average of these four slopes gives the next state:

$$ x_{n+1} = x_n + \frac{\Delta t}{6} \left(k_1 + 2k_2 + 2k_3 + k_4\right) $$

In our simulator, the state vector is:

$$ x = \begin{bmatrix} i \\ V_c \end{bmatrix} $$

It contains the circuit current and capacitor voltage. RK4 advances both quantities together through time.

The simulation uses a time step of (10^{-5}) seconds. A sufficiently small time step helps capture the rapid changes that occur during the transient response.

What Can We Observe?

The application presents four engineering plots:

  1. Capacitor voltage — how the capacitor charges and approaches its steady-state voltage.

  2. Circuit current — how current rises, oscillates, and eventually settles.

  3. Component voltages — the voltage drops across the resistor, inductor, and capacitor.

  4. Stored energy — how energy moves between the inductor's magnetic field and the capacitor's electric field.

The component-voltage plot demonstrates Kirchhoff's Voltage Law:


V_r+V_l+V_c=V_s

The energy plot is particularly interesting. The inductor stores magnetic energy, while the capacitor stores electric energy:

$$ E_L = \frac{1}{2}Li^2 $$ $$ E_C = \frac{1}{2}CV_c^2 $$

The total stored energy changes as the circuit responds to the input, while the resistor dissipates energy as heat.

Interactive Engineering with Julia

The real excitement begins when we move the sliders.

Changing resistance affects damping. Changing inductance or capacitance changes the natural frequency of the circuit. The simulator recalculates the response and updates the plots dynamically.

Julia makes this kind of project approachable because its mathematical syntax closely resembles the equations we write on paper. With GLMakie, we can connect numerical calculations to interactive graphical elements without building a separate application in another language.

From Circuit Theory to Scientific Computing

This small project demonstrates a powerful idea: engineering concepts can be explored through computation rather than only through textbook examples.

The same approach can be extended to:

  • Parallel RLC circuits

  • Resonance and frequency response

  • PID control systems

  • Mechanical spring-mass-damper systems

  • Heat transfer and fluid simulation

A few equations, a numerical solver, and an interactive interface can turn an abstract engineering topic into a virtual laboratory.

For me, this is one of the most enjoyable aspects of scientific computing with Julia — the ability to experiment with mathematics and immediately see the physical consequences of changing a parameter.

Source Code...


using GLMakie

############################
# 1. Simulation Parameters & ODE
############################

Vs = 10.0           # DC step voltage (Volt)
t_start = 0.0
t_end = 0.1
dt = 1e-5

t = collect(t_start:dt:t_end)
t_ms = t .* 1000.0

function rlc_derivatives(x, R, L, C, Vs)
    current = x[1]
    voltage = x[2]
    di_dt = (Vs - R * current - voltage) / L
    dVc_dt = current / C
    return [di_dt, dVc_dt]
end

function rk4_step(x, dt, R, L, C, Vs)
    k1 = rlc_derivatives(x, R, L, C, Vs)
    k2 = rlc_derivatives(x .+ 0.5 * dt .* k1, R, L, C, Vs)
    k3 = rlc_derivatives(x .+ 0.5 * dt .* k2, R, L, C, Vs)
    k4 = rlc_derivatives(x .+ dt .* k3, R, L, C, Vs)
    return x .+ (dt / 6.0) .* (k1 .+ 2.0 .* k2 .+ 2.0 .* k3 .+ k4)
end

function simulate_rlc(t, R, L, C, Vs)
    N = length(t)
    step_dt = t[2] - t[1]
    i = zeros(N)
    Vc = zeros(N)
    x = [0.0, 0.0]

    for k in 1:N
        i[k] = x[1]
        Vc[k] = x[2]
        if k < N
            x = rk4_step(x, step_dt, R, L, C, Vs)
        end
    end

    Vr = R .* i
    Vl = Vs .- Vr .- Vc
    E_inductor = 0.5 .* L .* i.^2
    E_capacitor = 0.5 .* C .* Vc.^2
    E_total = E_inductor .+ E_capacitor

    omega0 = 1.0 / sqrt(L * C)
    alpha = R / (2.0 * L)
    zeta = alpha / omega0

    regime = if zeta < 0.99
        "Underdamped"
    elseif zeta <= 1.01
        "Near Critical Damping"
    else
        "Overdamped"
    end

    return (
        i = i,
        Vc = Vc,
        Vr = Vr,
        Vl = Vl,
        E_inductor = E_inductor,
        E_capacitor = E_capacitor,
        E_total = E_total,
        omega0 = omega0,
        zeta = zeta,
        regime = regime
    )
end

############################
# 2. Interactive Figure & Sliders
############################

fig = Figure(size = (1250, 920), fontsize = 15, figure_padding = 20)

sg = SliderGrid(
    fig[1, 1:2],
    (label = "Resistance R (Ω)", range = 1.0:1.0:150.0, format = "{:.1f} Ω", startvalue = 20.0),
    (label = "Inductance L (mH)", range = 10.0:5.0:500.0, format = "{:.0f} mH", startvalue = 100.0),
    (label = "Capacitance C (μF)", range = 20.0:10.0:500.0, format = "{:.0f} μF", startvalue = 100.0),
    width = 900
)

R_obs = sg.sliders[1].value
L_obs = lift(val -> val * 1e-3, sg.sliders[2].value)
C_obs = lift(val -> val * 1e-6, sg.sliders[3].value)

sim_obs = lift(R_obs, L_obs, C_obs) do R, L, C
    simulate_rlc(t, R, L, C, Vs)
end

header_text = lift(sim_obs, R_obs, sg.sliders[2].value, sg.sliders[3].value) do sim, R, L_mH, C_uF
    "Series RLC Transient ($(sim.regime)) — R=$(round(R, digits=1)) Ω, L=$(round(L_mH, digits=0)) mH, C=$(round(C_uF, digits=0)) μF | ζ=$(round(sim.zeta, digits=3)), ω₀=$(round(sim.omega0, digits=1)) rad/s"
end

Label(fig[0, 1:2], header_text, fontsize = 18, font = :bold)

# Derived reactive observables for plotting
Vc_obs = lift(s -> s.Vc, sim_obs)
i_obs = lift(s -> s.i, sim_obs)
Vr_obs = lift(s -> s.Vr, sim_obs)
Vl_obs = lift(s -> s.Vl, sim_obs)
El_obs = lift(s -> s.E_inductor, sim_obs)
Ec_obs = lift(s -> s.E_capacitor, sim_obs)
Et_obs = lift(s -> s.E_total, sim_obs)

############################
# 3. Four Engineering Plots
############################

# Plot 1: Capacitor Voltage
ax1 = Axis(fig[2, 1], title = "Capacitor Voltage", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax1, t_ms, Vc_obs, color = :royalblue, linewidth = 2.5, label = "Vc(t)")
hlines!(ax1, [Vs], color = :gray50, linestyle = :dash, linewidth = 1.5, label = "Step Input ($(Vs) V)")
axislegend(ax1, position = :rb)

# Plot 2: Circuit Current
ax2 = Axis(fig[2, 2], title = "Circuit Current", xlabel = "Time (ms)", ylabel = "Current (A)")
lines!(ax2, t_ms, i_obs, color = :crimson, linewidth = 2.5, label = "i(t)")
hlines!(ax2, [0.0], color = :gray50, linestyle = :dot, linewidth = 1.2)
axislegend(ax2, position = :rt)

# Plot 3: Component Voltages
ax3 = Axis(fig[3, 1], title = "Component Voltages (Vr + Vl + Vc = Vs)", xlabel = "Time (ms)", ylabel = "Voltage (V)")
lines!(ax3, t_ms, Vr_obs, color = :darkorange, linewidth = 2.0, linestyle = :solid, label = "Resistor (Vr)")
lines!(ax3, t_ms, Vl_obs, color = :seagreen, linewidth = 2.0, linestyle = :dash, label = "Inductor (Vl)")
lines!(ax3, t_ms, Vc_obs, color = :royalblue, linewidth = 2.0, linestyle = :dot, label = "Capacitor (Vc)")
axislegend(ax3, position = :rt)

# Plot 4: Stored Energy
ax4 = Axis(fig[3, 2], title = "Stored Energy", xlabel = "Time (ms)", ylabel = "Energy (J)")
lines!(ax4, t_ms, El_obs, color = :seagreen, linewidth = 2.2, label = "Inductor Energy")
lines!(ax4, t_ms, Ec_obs, color = :royalblue, linewidth = 2.2, label = "Capacitor Energy")
lines!(ax4, t_ms, Et_obs, color = :black, linewidth = 1.8, linestyle = :dash, label = "Total Stored Energy")
axislegend(ax4, position = :rt)

# Keep y-limits readable across slider sweeps
on(sim_obs) do sim
    ylims!(ax2, extrema(sim.i) .* 1.15)
    ylims!(ax3, extrema(vcat(sim.Vr, sim.Vl, sim.Vc)) .* 1.15)
    ylims!(ax4, (0.0, max(maximum(sim.E_total) * 1.15, 1e-4)))
end
notify(sim_obs)

colgap!(fig.layout, 24)
rowgap!(fig.layout, 18)

screen = display(fig)
wait(screen)

Thursday, November 26, 2026

2014: Elon Musk Opens the Patent Wall. 1991: Bill Gates Warns Against It - Two different people. Two different philosophies. One question for every engineer...

In 2014, Elon Musk announced that Tesla would not initiate patent lawsuits against those using its technology in good faith.

His reasoning was simple: Tesla's mission was to accelerate the world's transition to sustainable energy. Why should patents prevent other engineers from contributing to that mission?

Musk believed that a growing electric-vehicle ecosystem would benefit everyone—including Tesla.

And engineers celebrated.

Now rewind to 1991.

Bill Gates, in an internal Microsoft memo, warned that if software patents had been widely taken out on existing ideas, the industry could have come to a complete standstill.

He understood the danger of turning fundamental ideas into corporate property.

Yet Microsoft later became an aggressive participant in the patent system.

The irony

Gates recognised the patent wall. Musk chose to open a door through it.

One warned that patents could suffocate innovation; the other demonstrated that a technology leader could choose openness over exclusivity.

What if Bharat had patented Zero?

Imagine if ancient Bharat had patented zero—the mathematical concept that transformed the decimal place-value system and became one of the foundations of modern computing.

What if every engineer, mathematician, and programmer had needed permission to use it?

The binary world of 0s and 1s, the digital revolution, the internet, and today's computing ecosystem would have faced an absurd barrier at their very foundation.

Bharat did not build a patent wall around zero. It gave the world a stepping stone.

The engineer's perspective

A patent can protect an invention. But it cannot guarantee innovation.

The engineer wants to solve problems, build upon existing knowledge, and create something better. The patent wall can turn that creative process into a legal obstacle course.

The question is not whether inventors deserve protection. They do.

The question is whether protecting an invention should become a means of controlling an entire technological ecosystem.

Musk's 2014 decision reminded us that true technological leadership is not merely about owning ideas—it is about enabling others to build upon them.

The future belongs to those who turn ideas into stepping stones, not walls.

And here I am... my write-up of 2011...

Saturday, November 21, 2026

A C++ serial task executor - influenced by earlier Android AsyncTask's serialexecutor...

AI-generated content but worth the effort...

This project is a C++20 re-creation of early Android AsyncTask (SERIAL_EXECUTOR): background work runs strictly one task at a time in FIFO order on a dedicated worker thread, while UI/progress/completion callbacks are marshaled back to a main/UI thread loop so you don't race on UI state.


High-Level Architecture & Threading Model


There are two distinct threads in the application:
  1. Main / UI Thread (main.cpp + MainThreadLoop)

    • Starts tasks via task.execute(params), triggering onPreExecute() immediately on the caller thread.

    • Drains queued UI callbacks (onProgressUpdate, onPostExecute) inside MainThreadLoop::pumpUntil(...).

  2. Background Worker Thread (SerialExecutor)

    • Owns a single std::thread (worker_) and a FIFO queue (std::deque<std::function<void()>>).

    • Executes one background callable to completion before popping the next one.

Plaintext
Main / UI Thread                          SerialExecutor Worker Thread
───────────────────                       ────────────────────────────
task1.execute(url1)
  └─▶ onPreExecute()  ──(enqueues)──▶ [ url1 task ]  ──▶ doInBackground(url1)
task2.execute(url2)                                        ├─ publishProgress() ──┐
  └─▶ onPreExecute()  ──(enqueues)──▶ [ url2 task ]  ◀─┘  (waits for url1)    │
                                                                               ▼
pumpUntil(...) ◀──────────────(posts callbacks)──────────────────── [ MainThreadLoop ]
  ├─ onProgressUpdate(25%, 50%...)                                     queue
  └─ onPostExecute(result)
       └─ ++completed; notifyWake()


Component-by-Component Breakdown


A. SerialExecutor (SerialExecutor.h / SerialExecutor.cpp)

  • FIFO Queue + Synchronization: Protects queue_ and stopping_ with a std::mutex, using std::condition_variable (cv_) so the worker sleeps with zero CPU spin when idle and wakes immediately when a task arrives or shutdown begins.

  • Why std::deque? Efficient O(1) push at the back (push_back) and O(1) pop at the front (pop_front), matching Android's ArrayDeque FIFO behavior.

  • Exception Containment: runLoop() wraps next_task() in try / catch (std::exception) and catch (...). If one background task throws, the worker logs it and keeps running subsequent tasks rather than terminating the thread and leaving queued work stuck forever.

  • Graceful Shutdown: shutdown() sets stopping_ = true under the lock, calls cv_.notify_all(), and joins worker_. Any task already queued before shutdown() is still drained before runLoop() exits; execute() rejects new tasks once stopping.


B. MainThreadLoop (MainThreadLoop.h / MainThreadLoop.cpp)

  • Acts as a lightweight stand-in for Android's Looper / Handler.

  • post(callback): Thread-safe producer method. Background threads (or any thread) push UI callbacks onto callbacks_ and call cv_.notify_one().

  • pumpUntil(should_stop): Runs on the main thread. Waits until either callbacks_ is non-empty or should_stop() returns true. It drains callbacks one at a time on the calling thread, exiting only once the queue is empty and should_stop() is true.

  • notifyWake(): Calls cv_.notify_all() to re-evaluate the condition variable predicate—essential when should_stop() depends on an external atomic counter (completed.load() >= 2) updated inside a callback.


C. AsyncTask<Params, Progress, Result> (async_task.h)

  • Template Parameters:

    • Params: Input passed to execute() and doInBackground().

    • Progress: Type passed to publishProgress() and received by onProgressUpdate().

    • Result: Return value of doInBackground() and input to onPostExecute().

  • Lifecycle Flow in execute(Params params):

    1. Calls onPreExecute() synchronously on the caller/UI thread.

    2. Enqueues a lambda onto SerialExecutor that runs doInBackground(std::move(p)) on the worker thread.

    3. Inside doInBackground, subclasses can call publishProgress(pct), which posts a lambda to MainThreadLoop so onProgressUpdate runs on the UI thread.

    4. Once doInBackground returns res, another lambda is posted to MainThreadLoop to invoke onPostExecute(std::move(res)) on the UI thread.


D. DownloadTask & main() (main.cpp)

  • DownloadTask specializes AsyncTask<std::string, int, std::string>, simulating progress steps (25, 50, 75, 100) every 150 ms.

  • Because SerialExecutor has only one worker thread, task2 starts only after task1 finishes doInBackground—even though both onPreExecute() calls run right away.

  • main() pumps MainThreadLoop until completed reaches 2, then shuts down SerialExecutor cleanly.


The Source Code...


MainThreadLoop.h
#pragma once

#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>

class MainThreadLoop {
public:
void post(std::function<void()> callback);

// Drains callbacks until `should_stop()` returns true and the queue is empty.
void pumpUntil(const std::function<bool()>& should_stop);
void notifyWake();

private:
std::mutex mutex_;
std::condition_variable cv_;
std::deque<std::function<void()>> callbacks_;
};

MainThreadLoop.cpp
#include "MainThreadLoop.h"

#include <utility>

void MainThreadLoop::post(std::function<void()> callback) {
if (!callback) {
return;
}
{
std::lock_guard<std::mutex> lock(mutex_);
callbacks_.push_back(std::move(callback));
}
cv_.notify_one();
}

void MainThreadLoop::pumpUntil(const std::function<bool()>& should_stop) {
while (true) {
std::function<void()> cb;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this, &should_stop] {
return !callbacks_.empty() || (should_stop && should_stop());
});

if (callbacks_.empty() && should_stop && should_stop()) {
return;
}

if (!callbacks_.empty()) {
cb = std::move(callbacks_.front());
callbacks_.pop_front();
}
}
if (cb) {
cb();
}
}
}

void MainThreadLoop::notifyWake() {
cv_.notify_all();
}

SerialExecutor.h
#pragma once

#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>

class SerialExecutor {
public:
SerialExecutor();
~SerialExecutor();

SerialExecutor(const SerialExecutor&) = delete;
SerialExecutor& operator=(const SerialExecutor&) = delete;

void execute(std::function<void()> task);
void shutdown();

private:
void runLoop();

std::mutex mutex_;
std::condition_variable cv_;
std::deque<std::function<void()>> queue_;
bool stopping_ = false;
std::thread worker_;
};

SerialExecutor.cpp
#include "SerialExecutor.h"

#include <exception>
#include <iostream>
#include <utility>

SerialExecutor::SerialExecutor()
: worker_([this] { runLoop(); }) {}

SerialExecutor::~SerialExecutor() {
shutdown();
}

void SerialExecutor::execute(std::function<void()> task) {
if (!task) {
return;
}
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
return;
}
queue_.push_back(std::move(task));
}
cv_.notify_one();
}

void SerialExecutor::shutdown() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) {
return;
}
stopping_ = true;
}
cv_.notify_all();
if (worker_.joinable()) {
worker_.join();
}
}

void SerialExecutor::runLoop() {
while (true) {
std::function<void()> next_task;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] {
return stopping_ || !queue_.empty();
});

if (queue_.empty() && stopping_) {
return;
}

next_task = std::move(queue_.front());
queue_.pop_front();
}

try {
next_task();
} catch (const std::exception& ex) {
std::cerr << "[SerialExecutor] Task threw: " << ex.what() << "\n";
} catch (...) {
std::cerr << "[SerialExecutor] Task threw unknown exception\n";
}
}
}

Asynctask.h

#pragma once

#include "MainThreadLoop.h"
#include "SerialExecutor.h"

#include <utility>

template <typename Params, typename Progress, typename Result>
class AsyncTask {
public:
AsyncTask(SerialExecutor& executor, MainThreadLoop& main_loop)
: executor_(executor), main_loop_(main_loop) {}

virtual ~AsyncTask() = default;

AsyncTask(const AsyncTask&) = delete;
AsyncTask& operator=(const AsyncTask&) = delete;

void execute(Params params) {
onPreExecute();

executor_.execute([this, p = std::move(params)]() mutable {
Result res = doInBackground(std::move(p));
main_loop_.post([this, r = std::move(res)]() mutable {
onPostExecute(std::move(r));
});
});
}

protected:
virtual void onPreExecute() {}
virtual Result doInBackground(Params params) = 0;
virtual void onProgressUpdate(const Progress& progress) {}
virtual void onPostExecute(Result result) {}

void publishProgress(Progress progress) {
main_loop_.post([this, prog = std::move(progress)]() {
onProgressUpdate(prog);
});
}

private:
SerialExecutor& executor_;
MainThreadLoop& main_loop_;
};

Main.cpp

#include "AsyncTask.h"
#include "MainThreadLoop.h"
#include "SerialExecutor.h"

#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>

class DownloadTask : public AsyncTask<std::string, int, std::string> {
public:
DownloadTask(SerialExecutor& exec,
MainThreadLoop& ui,
std::atomic<int>& completed_counter)
: AsyncTask(exec, ui),
ui_(ui),
completed_counter_(completed_counter) {}

protected:
void onPreExecute() override {
std::cout << "[UI] Starting download task...\n";
}

std::string doInBackground(std::string url) override {
for (int pct : {25, 50, 75, 100}) {
std::this_thread::sleep_for(std::chrono::milliseconds(150));
publishProgress(pct);
}
return "Downloaded: " + url;
}

void onProgressUpdate(const int& progress) override {
std::cout << "[UI] Progress: " << progress << "%\n";
}

void onPostExecute(std::string result) override {
std::cout << "[UI] Done -> " << result << "\n";
++completed_counter_;
ui_.notifyWake();
}

private:
MainThreadLoop& ui_;
std::atomic<int>& completed_counter_;
};

int main() {
SerialExecutor serial_executor;
MainThreadLoop main_loop;
std::atomic<int> completed{0};

DownloadTask task1(serial_executor, main_loop, completed);
DownloadTask task2(serial_executor, main_loop, completed);

task1.execute("https://example.com/file1.zip");
task2.execute("https://example.com/file2.zip");

main_loop.pumpUntil([&completed] {
return completed.load() >= 2;
});

serial_executor.shutdown();
return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 4.4)
project(SerialTaskExecutor LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Threads REQUIRED)

add_executable(SerialTaskExecutor main.cpp
SerialExecutor.cpp
SerialExecutor.h
MainThreadLoop.cpp
MainThreadLoop.h
AsyncTask.h)

target_link_libraries(SerialTaskExecutor PRIVATE Threads::Threads)

Result...

[UI] Starting download task...
[UI] Starting download task...
[UI] Progress: 25%
[UI] Progress: 50%
[UI] Progress: 75%
[UI] Progress: 100%
[UI] Done -> Downloaded: https://example.com/file1.zip
[UI] Progress: 25%
[UI] Progress: 50%
[UI] Progress: 75%
[UI] Progress: 100%
[UI] Done -> Downloaded: https://example.com/file2.zip