Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encountered race even after using std::atomic types

Can you please tell me if the following code is thread safe?

I think I am encountering a race condition, because Task2 does not get executed even though I have set the value of params.b to be true from the GUI.

struct params { 
    params() {}
    ~params() {}
    atomic_bool a;
    atomic_bool b;
};

struct driver { 
    driver() {}
    ~driver() {}

    params myParams;

    void tFun() {
        while (1) {
            if (myParams.a) { /* DoTask1 */ }
            if (myParams.b) { /* DoTask2 */ }
        }
    }

    void DoSome() {
        std::thread t(&driver::tFun, this);
        t.detach();
        while (1) {
            myParams.a = fromGui.val;
            myParams.b = fromGui.val;
        }
    }
};

int main() {
    driver myDriver;
    myDriver.DoSome();
    return 0;
}

Please execuse my 'fromGui.val' usage, it is supposed to indicate that this value will be loaded from the GUI.

like image 958
The Vivandiere Avatar asked Jun 18 '26 07:06

The Vivandiere


1 Answers

The situation I can see is that there is a race between fTun() function and DoSome():

For example:

1. DoSome() sets a,b true 
2. tFun() executes in while loop, as a is true, it starts DoTask1
2. DoSome() sets a,b to false
3. tFun() finishes DoTask1 and come to check myParams.b which is false;
   DoTask2 is ignored!!
4. loop continues to step 1

If you always set a,b to true, then there is no race to compare with, tasks DoTask1 & DoTask2 should both be executed

like image 63
billz Avatar answered Jun 20 '26 21:06

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!