Thread Safety and static functions
c++, multithreading
Solution
Yes, your constructor is thread safe, because it accesses only instance variables (specifically, `d`). It does exhibit undefined behavior, because it reads from uninitialized `d` to perform the increment, but that has nothing to do with thread safety.
Here is how you can fix undefined behavior:
base(): d(0) {f(this);};
Now that `d` is initialized in the initializer list, your program behaves in a predictable way.
Problem
Let's suppose I have a : ``` class base { base(){f(this);}; static void f(base * b) {(b->d)++;}; int d; }; ``` Now if on 2 separate threads I create an object of type base, would method `f` be considered thread safe? I am asking this question because usually from what I know is that for a method to be thread safe it should not use static members nor global variables. But as you can see from the above example I decided not to make variable `d` static, instead I call it through the running instance of base. Also, I think I don't need to protect this line : `(b->d)++;` with a mutex since each thread will have a separate instance of base and of variable d. Am I correct in my analysis? is there anything I should be careful about?