I understand the concept of thread safety. I am looking for tips to simplify thread safety when trying to protect a single variable.
Let's 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 that I can come up with, but they both have unpleasant flaws. The first is to create a thread protected class to store 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 it will keep aPass completely safe, nothing can be wrong and ever touch it, YAY! however, look at this whole mess and imagine the confusion when accessing it. gross.
Another way is to make them available and make sure you lock the mutex before using aPass.
pthread_mutex_lock(aPass_lock); do something with aPass pthread_mutex_unlock(aPass_lock);
But what if someone new comes to the project, what if you forget once to block it. I do not like to debug problems with threads, they are complicated.
Is there a good way (using pthreads, because I have to use QNX, which has a little support support). To lock individual variables without a large class, and it's safer, just create a mutex lock to go with it?