On 22/12/2022 20:41, Frederick Virchanza Gotham wrote:
>
> I don't know if I've re-invented the wheel here but I can't remember
> having seen something like this in the C++ standard library nor Boost
> nor wxWidgets.
>
> Let's say we have a multi-threaded program, it has a main GUI thread
> and five worker threads, giving a total of six threads.
>
> The program at all times has a status string, which is a global
> 'std::string' object. All six threads read and write the global
> status string.
>
I'd say that's your problem right there.
Only allow /one/ thing to change a given variable. Problem solved.
(Well, /almost/ solved - you might still need something to ensure
changes are seen atomically by readers, depending on how your strings
work and get updated.)
I try to think of programming like electronics. Devices have inputs and
outputs. It's okay to drive multiple inputs from one output, but if you
try to drive one line from multiple outputs, things are going to go
wrong (such as letting out the magic grey smoke that runs all electronics).
When you have six devices that all have an error indicator output, you
don't just join them together on one red LED. You make six error LEDs,
one for each device. Or you use a multiplexer, such as an OR gate, to
combine the signals safely.
Do the same in your programming.
So you have six separate status strings, and a "multiplexer" that
combines them in some way. Maybe it serialises them to a log file, or
joins them together for display, or prioritises them to show error
messages at higher priority than "okay" messages. Maybe this is done by
a single "update" function (which may need locking if called from
different threads), or it is in a separate thread connected by queues to
the original threads, or it is in a timer function called periodically
in the gui thread. There are many options.
But the worst idea is to have one thread set the status to "There's a
meltdown on it's way" only to have it immediately overwritten by another
thread saying "Everything's hunky-dory over here".