Using const bool link to track background task cancellation? (C ++)

I have a desktop application where certain calculations, when requested by the user, are performed in the background thread. Cancel button.

I know the “safe” or “right” ways to cancel signaling in the background job (using Qt signal / slot connections, mutex-wrapped buffers, which background tasks are polled for, etc.).

However, the simplest thing, it seems to me, is bool cancelledin my class the main thread, which is installed synchronously when the Cancel button is pressed and transferred const bool &cancelledto the background thread on which it polls.

Is there any realistic way this approach can have unpleasant consequences?

+4
source share
2 answers

Streams can run on separate processors, each with its own cache. If the boolean is atomic, you can do it. Otherwise, you risk that the change applies only to the nearest cache and does not appear in another thread.

+5
source

As long as you respect the intricacies of Internet access to data (in MSVC, the flag variable must be mutable *, either set it atomically, or execute a write barrier afterwards), that's fine. This is a fairly common approach.

* volatile , MSVC .

+2

All Articles