2026-11-03 (3): Multithreading, Project Talk#

Multithreading, And Race Conditions#

Doing Multiple Things In Parallel#

Here’s a sketch running the PLC loop and the commandline loop in parallel, using multithreading.

#include <print>
#include <thread>
#include <unistd.h>


class Motor
{
public:
    enum Direction { FORWARD, BACKWARD, NONE };
    void forward() { _direction = FORWARD; }
    void backward() { _direction = BACKWARD; }
    void stop() { _direction = NONE; }

private:
    Direction _direction;
};

class FSM
{
public:
    enum State { OPEN, CLOSED, OPENING, CLOSING };

public:
    FSM(Motor& motor) : _motor(motor), _state(OPEN) {}

    State state() const { return _state; }
    const char* state_str() const
    {
        switch (_state) {
            case OPEN: return "OPEN"; 
            case CLOSED: return "CLOSED";
            case OPENING: return "OPENING"; 
            case CLOSING: return "CLOSING";
        }
        return "OJE";
    }
    
    void dwim_pressed()
    {
        switch (_state) {
            case OPEN:
                _motor.backward();
                _state = CLOSING;
                break;
            case CLOSED:
                _motor.forward();
                _state = OPENING;
                break;
            case OPENING:
                _motor.backward();
                _state = CLOSING;
                break;
            case CLOSING:
                _motor.forward();
                _state = OPENING;
                break;
        }        
    }
    void open_position_reached()
    {
        switch (_state) {
            case OPEN:
                std::println("wtf?");
                break;
            case CLOSED:
                std::println("wtf?");
                break;
            case OPENING:
                _motor.stop();
                _state = OPEN;
                break;
            case CLOSING:
                std::println("wtf?");
                break;
        }        
    }
    void closed_position_reached()
    {
        switch (_state) {
            case OPEN:
                std::println("wtf?");
                break;
            case CLOSED:
                std::println("wtf?");
                break;
            case OPENING:
                std::println("wtf?");
                break;
            case CLOSING:
                _motor.stop();
                _state = CLOSED;
                break;
        }        
    }

private:
    Motor _motor;
    State _state;
};

class Button
{
public:
    bool is_pressed() { return true; }
};


Motor motor;
FSM fsm(motor);

Button dwim;
Button closed_position;
Button open_position;

void plc_loop()
{
    // PLC loop
    while (true) {
        if (dwim.is_pressed())
            fsm.dwim_pressed();
        if (closed_position.is_pressed())
            fsm.closed_position_reached();
        if (open_position.is_pressed())
            fsm.open_position_reached();

        std::println("state: {}", fsm.state_str());

        sleep(1);
    }
}

void cmdline_loop()
{
    while (true) {
        char buffer[1024] = {0};
        ssize_t nread = read(0, buffer, sizeof(buffer)-1);
        if (nread == -1) {
            perror("read");
            break;
        }

        std::println("debug line: {}", buffer);

        std::string line = buffer;
        if (line == "dwim\n")
            fsm.dwim_pressed();

        std::println("state: {}", fsm.state_str());
    }
}

int main()
{
    std::thread plc_thread(plc_loop);
    std::thread cmdline_thread(cmdline_loop);

    plc_thread.join();
    cmdline_thread.join();

    return 1;
}

The Consequences Of Doing Multiple Things In Parallel#

Livehacked …

#include <print>
#include <thread>

uint64_t the_number = 0;

void increment_10_000_000_times()
{
    uint64_t n_loops = 10'000'000;
    while (n_loops--) {
        the_number++;
    }
}


int main()
{
    std::thread t1(increment_10_000_000_times);
    std::thread t2(increment_10_000_000_times);

    t1.join();
    t2.join();

    std::println("the_number: {}", the_number);
    return 0;
}
  • Expected output: 20000000

  • Actual output (varies): 10475662

$ ./2026-11-03-mother-of-all-race-conditions
the_number: 10475662

Project: First Tasks#

Door Finite State Machine#

Test driven development of the FSM class in the middle. Cornerstones:

  • Knows the motor (see below) ⟶ defines the interface

  • Does not know any button. Rather, provides methods (like, “dwim pressed”, “open position reached”, “closed position reached”) to inject events that might have their origins in buttons - but not necessarily. (See Door Commandline)

Buttons: Edge Detection#

Button interface is level based - you ask it whether its state is “pressed” or “released”.

The FSM wants events that we need compute from the levels, in a 1ms PLC polling loop.

Around a Button, wrap another object that can be asked if an edge (configurable: rising, falling) has been detected. UML might look like this:

@startuml

interface Button {
  + is_pressed()
}
class MockButton {}
class LibGPIODButton {}
Button <|.. MockButton
Button <|.. LibGPIODButton

class EdgeDetector {
  + is_edge()
}
EdgeDetector -r-> Button

@enduml

Keep an eye on followup task “debouncing”.

Hardware: GPIO On The Pi#

  • Setup a Pi

  • Do some research on libgpiod (a library to control GPIOs on Linux)

  • Focus on immediate feature (see Buttons: Edge Detection): input, level based. Goal is to implement LibGPIODButton in the UML diagram from Buttons: Edge Detection

  • Keep an eye on hardware based edge detection and debouncing which will be one of the next steps

Door Commandline#

Create a program that can be used to manually test the FSM. That program …

  • Instantiates a dummy Motor implementation (derived from interface Motor as defined by the FSM).

    As a first step, this implementation would simply output something like “left”, “right”, “stop” in calls to the methods with the same name.

  • Instantiates a FSM instance which knows the motor.

  • Reads from stdin in a loop, like cmdline_loop() in the sample program in Doing Multiple Things In Parallel.

    The program does not use multithreading like the sample program does.

    Check how the readline library can be used in place of raw read(STDIN_FILENO, ...), to provide history browsing.

  • Understands commands that drive the FSM, or report state, like …

    • DWIM button pressed

    • Open position reached

    • Closed position reached

    • Report motor state (left, right, stopped)

    • Report FSM state

    • …

Motor#

The door’s stepper motor is controlled by a A4988 chip. The A4988 requires two GPIO pins configured as output for direction/enable, and a PWM pin for the motor speed.

  • Goal 1: define interfaces for Switch and PWMPin

  • Goal 2: based on mock implementations of those, write a number of tests.

  • Goal 3: make tests run.

@startuml

interface Motor {
  + set_direction()
}

interface Switch {
  + set_state()
}
interface PWMPin {
  + set_period()
  + set_duty_cycle()
}

A4988_Motor -up-|> Motor
A4988_Motor -right-> "direction 1" Switch
A4988_Motor -right-> "enable 1" Switch
A4988_Motor -right-> PWMPin

@enduml