0

Consider the following piece of multiple - threaded code -

#include <iostream>
#include <thread>
using namespace std;
int a = 0;
bool alive = 1, start = 0;
void detector()
{
    int local_a = 0;
    while (alive)
    {
        if (start)
        {
            if (a != local_a)
            {
                cout << " change detected!\n";
                local_a = a;
            }
            start = 0;
        }
    }
}
int main(int argc, char *argv[])
{
    std::thread t(detector);
    int count = 10;
    while (count--)
    {
        a = rand();
        start = 1;
        cout << a << '\n';
        while (start)
        {
        };
    }
    alive = 0;
    t.join();
    return 0;
}

My question is, is this architecture thread safe (except for consol logging part where printed text might get mixed but it is done our convenience, not the part of my working code so i only care about if my variables are having data-race)? I know i haven't used any mutex but anywhere where read and write occurs simultaneously between two threads, one thread is just waiting to see a particular value and one is writing. So no matter what the order of read-write of those threads are, one thread is always reading it again to detect a particular write (a single operation).

I have ran this on my machine and works correct but I don't know if it can show undefined behaviour on other machines so i just want to confirm.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • 1
    Yes, that's undefined behavior. Non-atomic objects may not be written in one thread and accessed by another thread without synchronization. And compilers _will_ compile this to behavior that you do not expect. – user17732522 Jul 27 '23 at 08:58
  • 1
    Does this answer your question? [Do I have to use atomic for "exit" bool variable?](https://stackoverflow.com/questions/16111663/do-i-have-to-use-atomicbool-for-exit-bool-variable), https://stackoverflow.com/questions/58516052 – user17732522 Jul 27 '23 at 09:01
  • But i ran it for a million times means ```count = 1000000``` and modified the code to print number of times ```a``` was changed and it was detected by ```detector``` thread and it was in sink upto million times since first main thread writes and then set ```start``` to 1 to invoke ```detector``` and main threads's loop waits(keep reading) it to finish(to ```detector```set ```start``` to 0) and once done then process starts to repeat again so how can they go out of sink? I am worried about the thing that one thread is reading again and again while another thread writing can cause some issues – Suryansh Dey Jul 27 '23 at 09:12
  • 1
    As I said: It _is_ undefined behavior. There is no guarantee whatsoever how it will behave, neither in theory nor in practice. Observation is irrelevant when faced with undefined behavior. See the linked duplicates (and other questions linked in them) for details. – user17732522 Jul 27 '23 at 09:14
  • @user17732522 can this lead to occasional segmentation fault segmentation fault (for god sake say yes... Plzzzz) – Suryansh Dey Jul 27 '23 at 10:15
  • A segmentation fault is a permitted outcome of undefined behavior and for example Clang does perform certain optimizations based on this UB that could likely cause segmentation faults in the code you have shown, yes. However, that is in all cases I have experienced so far not "occasionally", but pretty much in every run if the compiler made that optimization. But there is nothing preventing it from happening occasionally either. – user17732522 Jul 27 '23 at 11:51
  • Can you please explain me in a bit details that why data race lead to UB? I mean since one thread is writing while another is reading, may be reading thread end up reading something wrong but how can it lead to crash my program i mean at most it can give me incorrect output but how seg fault? Why other parts of the code is getting affected?? – Suryansh Dey Jul 27 '23 at 13:20

0 Answers0