Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety Of a single variable

I understand the concept of thread safety. I am looking for advice to simplify thread safety when trying to protect a single variable.

Say I have a variable:

double aPass;

and I want to protect this variable, so i create a mutex:

pthread_mutex_t aPass_lock;

Now there are two good ways i can think of doing this but they both have annoying disadvantages. The first is to make a thread safe class to hold the variable:

class aPass {
    public:
        aPass() {
            pthread_mutex_init(&aPass_lock, NULL);
            aPass_ = 0;
        }

        void get(double & setMe) {
            pthread_mutex_lock(aPass_lock);
            setMe = aPass_
            pthread_mutex_unlock(aPass_lock);
        }

        void set(const double setThis) {
            pthread_mutex_lock(aPass_lock);
            aPass_ = setThis;
            pthread_mutex_unlock(aPass_lock);
        }
    private:
        double aPass_;
        pthread_mutex_t aPass_lock;
};

Now this will keep aPass totally safe, nothing can be mistaken and ever touch it, YAY! however look at all that mess and imagine the confusion when accessing it. gross.

The other way is to have them both accessible and to make sure you lock the mutex before you use aPass.

pthread_mutex_lock(aPass_lock);
   do something with aPass
pthread_mutex_unlock(aPass_lock);

But what if someone new comes on the project, what if you forget one time to lock it. I don't like debugging thread problems they are hard.

Is there a good way to (using pthreads because i have to use QNX which has little boost support) To lock single variables without needing a big class and that is safer then just creating a mutex lock to go with it?

like image 724
Fantastic Mr Fox Avatar asked Nov 09 '12 01:11

Fantastic Mr Fox


People also ask

Are variables thread-safe?

On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.

Why singleton is not thread-safe?

Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.

How do you make a singleton class thread-safe volatile?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.


1 Answers

std::atomic<double> aPass;

provided you have C++11.

like image 107
Pete Becker Avatar answered Nov 03 '22 05:11

Pete Becker