Re: Share .cpp and .h along projects
On Wed, 29 Aug 2007 17:31:15 -0500, "Ben Voigt [C++ MVP]"
<rbv@nospam.nospam> wrote:
The release part of the operation was able to use a volatile write in
VC2005
and avoid the function call. That wouldn't be correct without volatile.
The "release" part of the operation (on those platforms where it actually
has meaning) occurs due to using the InterlockedXXX API. It is not
necessary for *you* to declare *your* pointer volatile.
A volatile assignment works perfectly well for the "release" operation:
You used the InterlockedXXX API in your example. As I said, you don't need
to declare your pointer volatile for that to work. If you want to change
the example and get rid of InterlockedXXX for the "release", I suppose it's
fine in VC2005 and later as long as the pointer is volatile. Note well,
however, that the volatile semantics MS introduced in VC2005 are quite
extraordinary (in at least two ways), and given that InterlockedXXX works
fine all by itself, without volatile, one would really have to be pining
away for volatile to use this unwise combination of InterlockedXXX and the
VC2005 volatile.
std::vector* volatile g_sharedVector;
...
{
std::vector* pvector = NULL;
// this is a spin-wait, efficient on SMP, but on a single processor
system a yield should be inserted
while (pvector == NULL) {
pvector = InterlockedExchangePointerAcquire(&g_sharedVector, NULL);
}
// use pvector in any way desired
g_sharedVector = pvector;
}
Your example, as originally stated, was intended to illustrate your earlier
claim:
any larger object can be controlled in a threadsafe
manner using a volatile pointer (which is word-sized) and memory barriers.
If you use InterlockedExchangePointer for the "release", which you did
until now, then you don't need volatile. (And you need the very special
VC2005 volatile for your new idea to work.) For uniprocessor and x86 SMP,
memory barriers aren't relevant. It should finally be noted that pointer
variables aren't essential to the technique you presented.
--
Doug Harrison
Visual C++ MVP