6

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?

5
  • 1
    you are correct, as long as the base pointers are thread specific you are good. Commented Dec 28, 2012 at 5:22
  • Are you able to compile your program? It should throw up a compilation error Commented Dec 28, 2012 at 5:22
  • @stamhaney, no I haven't I am just trying to work out the theory :) please point out the problem though Commented Dec 28, 2012 at 5:23
  • The constructor should be under public access Commented Dec 28, 2012 at 5:26
  • Doesn't HAVE to be under public access (singletons are generally made with private/protected constructors), but for most use cases, sure. I think it's clear this is just an example, though, and the brain's compiler is much more relaxed than the CPU's. Commented Dec 28, 2012 at 5:55

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.