2026-11-09 (3): C++ (enum Variations), Multithreading (And Lambda), Project Talk#

C++: enum class …#

C++: Multithreading: How Threads Are Started#

Parallel FSM Loops: void func(void), And Global Variables#

Continuing with code from Doing Multiple Things In Parallel

  • plc_loop(): PLC, polling inputs in 1ms loop, and converting what has been found to FSM events

  • cmdline_loop(): injecting FSM events directly from commandline

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


class FSM
{
public:
    void dwim_pressed()
    {
        std::println("FSM event: dwim_pressed");
    }
    void open_position_reached()
    {
        std::println("FSM event: open_position_reached");
    }
    void closed_position_reached()
    {
        std::println("FSM event: closed_position_reached");
    }

private:
    // ... omitted ...
};

class Button
{
public:
    Button()
    : _generator(_device()),      // seed generator
      _distribution((1.0 / 10.0)) // 1.0 / 10.0 means a 10% chance of returning true
    {}

    bool is_pressed()
    {
        return _distribution(_generator);
    }

private:
    std::random_device _device; 
    std::mt19937 _generator;
    std::bernoulli_distribution _distribution;
};


void plc_loop(FSM& fsm, Button& dwim, Button& open_position, Button& closed_position)
{
    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();

        sleep(1);
    }
}

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

        std::string line = buffer;  // convert to string for better
                                    // "==" semantics (pure decadence)
        if (line == "dwim\n")
            fsm.dwim_pressed();
    }
}

int main()
{
    Button dwim;
    Button closed_position;
    Button open_position;
    FSM fsm;

    std::thread plc_thread(plc_loop, std::ref(fsm), std::ref(dwim), std::ref(open_position), std::ref(closed_position));
    std::thread cmdline_thread(cmdline_loop, std::ref(fsm));

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

    return 0;
}

Passing Thread-Function Parameters#

  • Global variables are bad (why?)

  • ⟶ pass parameters

int main()
{
    return 0;
}