Project

General

Profile

Signals and threads - safe or not??

Added by Mark Travis over 1 year ago

I'm in the process of building the final part of my app, and I need the "computing engine" on a separate thread so I don't block the user interface (UI.)

During the processes undertaken by the "computing engine" I need a way to send signals from the UI.

I used the BroadCast example to learn how to send packages/structures/objects FROM the "computing engine" to the UI. I believe that example is considered thread safe. I don't see a way for race conditions or blocking to occur since it's using locks and mutex the way I would expect.

However, I was thinking a Signal would be the best way to handle something coming from the UI. But I saw on a thread from 2019 that Roel said Wt::Signal was NOT thread safe.

Can anyone confirm that?

Should I use boost::signals2 instead, in parallel with the BroadCast example technique?

The "computing engine" loops while it does its processing and I have a binary flag to halt processing. I planned to use the Signal to set the binary flag to stop the compute and return the results.


Replies (4)

RE: Signals and threads - safe or not?? - Added by Roel Standaert over 1 year ago

Wt's signals are indeed not thread safe by design. Their intended use is to dispatch signals within a WApplication context while the UpdateLock is held.

You can use any system to send messages to your separate thread, that's left outside of the scope of Wt. If you only have a binary flag a simple std::atomic_bool should do the trick.

RE: Signals and threads - safe or not?? - Added by Mark Travis over 1 year ago

Thanks Roel,

I found this over the weekend: https://thispointer.com/c11-how-to-stop-or-terminate-a-thread/

I'll look at std::atomic_bool. Simpler is always better.

This is indeed an inter-process, within WApplication, type of issue. I have a "control" module that spawns a thread to do some work with periodic feedback to the control module.

I want to give the user a "stop" button in case the work effort is going in the wrong direction.

When the thread is finished, it re-attaches to the control module. This frees up the UI and also allows me to burn a few extra CPU cores to speed things up.

RE: Signals and threads - safe or not?? - Added by Roel Standaert over 1 year ago

By the way, if you're using C++20 you may want to look at std::jthread: https://en.cppreference.com/w/cpp/thread/jthread

It has this functionality built-in: https://en.cppreference.com/w/cpp/thread/jthread/request_stop

RE: Signals and threads - safe or not?? - Added by Mark Travis over 1 year ago

Wow, yes, jthread seems to be the answer.

    (1-4/4)