Re: C++ Threads, what's the status quo?
"Jeff Koftinoff" <jeff.koftinoff@gmail.com> wrote in message
news:1168894217.664801.296830@51g2000cwl.googlegroups.com...
JohnQ wrote:
template<class T>
Volatile
{
LockHandle my_lock;
T my_data;
public:
.
.
.
Volatile<T>& operator=(const T& a)
{
AutoLock lock(my_lock); // AutoLock is a mutex wrapper class
if(this != &a)
{
my_data = a;
}
return *this;
}
};
Volatile<int> x; // global x
void set_volatile_global_var(int a) // func called by multiple threads
{
x = a; // synchronized operation on the data
}
Three problems:
#1. Your lock is private
#2. The lock is only used when my_data is set via operator =.
#3. There is no other way to read or modify my_data
Any accesses of my_data must be protected by the lock. If you added a
method to read my_data, even if that method performed the lock, if the
user wanted to read it, modify it, and then set it, then the user must
perform the lock. And it must be the same lock, otherwise you end up
with deadlock potentials. Furthermore, if this object was used in a
larger object which also needed a lock, then all the locks down the
line must be aquired in the proper order whenever any change occurs
I wrote it wrong also. AutoLock thakes a Mutex& rather than a LockHandle. Oh
well, so much for late night hacking without trying the code first huh.
Still, I'm sure one can come up with something similar combined with a smart
ptr and get the right effect.
John
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]