Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety and static functions

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?

like image 503
Kam Avatar asked Dec 28 '12 05:12

Kam


People also ask

Are static functions thread safe?

No, static functions are not inherently thread-safe. Even your simple example isn't. Assuming both intvariable and stringvariable are supposed to be updated at the same time, another thread could observe the state of c1 between the two assignments, leading to data corruption.

What are thread safe functions?

A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. In C language, local variables are dynamically allocated on the stack.

How do I make a static variable thread safe?

As for the original question - Hashtable by itself is synchronized. So, if you are declaring a static final Hashtable and also intializing it at the time of declaration itself, all operations will be thread-safe on this Hashtable instance without you having to write any code for synchronization.

How do you ensure thread safety?

The best way to achieve thread safety is to avoid shared state. For the state, you need to share you can either use message parsing together with immutable classes or the concurrent data structures together with synchronized blocks and volatile fields.


1 Answers

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.

like image 118
Sergey Kalinichenko Avatar answered Sep 21 '22 00:09

Sergey Kalinichenko