Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const bool reference for background task cancellation tracking? (C++)

I have a desktop application where certain computations, when requested by the user, are run in a background thread. There is a cancel button.

I know the "safe" or "correct" ways of signaling cancellation to the background task (using Qt signal/slot connections, mutex-wrapped booleans on which the background task polls, etc.).

However, the simplest thing seems to me to be having a bool cancelled in my main-thread class, which is set synchronously when the Cancel button is pressed, and passing a const bool &cancelled to the background thread, on which it polls.

Is there any realistic way this approach can backfire?

like image 699
Andrey Mishchenko Avatar asked Mar 17 '23 02:03

Andrey Mishchenko


1 Answers

The threads may run on separate processors, each with its own cache. If the boolean is atomic you can do this. Otherwise you risk that a change is only propagated as far as the nearest cache, and not visible to the other thread.

like image 58
Cheers and hth. - Alf Avatar answered Mar 19 '23 18:03

Cheers and hth. - Alf