Boost logo

Boost :

From: Matt Hurd (matt.hurd_at_[hidden])
Date: 2004-09-20 07:55:04


On Mon, 20 Sep 2004 13:33:50 +0100, Puverle, Tomas (IT)
<tomas.puverle_at_[hidden]> wrote:
> > The Win32 API provides InterlockedXXX for atomic operations
> > on long data types, e.g. InterlockedIncrement. I am not sure
> > about other OS's, but it should be possible to define an
> > atomic_long class:
> >
> > class atomic_long
> > {
> > private: long val;
> > public:
> > inline atomic_long & operator++()
> > {
> > InterlockedIncrement( &val );
> > return( *this );
> > }
> > // ...
> > };
>
> I think this design could cause problems - presumably, there would need
> to be a way to test the value of the atomic_long, such as
> operator==(long), but that could lead to problematic code:
>
> if (++myAtomicLong == someValue)
> //...
> else
> //...
>
> An easy fix would be to make the return type void.

Not quite what you want I think.

This is going off on a separate tangent to the style of atomic memory
op I was talking about but anyway, we are here...

This is how I do it. I refer to the interlocked op this way:

    /// \brief Simple class wrapper for raw atomic functions
    class atomic_op_interlocked
    {
    public:

        /// \brief Increment a value
        /// \return The incremented value.
        template< typename WordType>
        static WordType inc(WordType& v)
        {
            BOOST_STATIC_ASSERT(sizeof(WordType) == sizeof(LONG));
            return static_cast<WordType>( InterlockedIncrement
(reinterpret_cast< LONG volatile *>( &v ) ));
        }
 
You'll notice the InterlockedIncrement return the incremented value,
you can use this instead of the value of the wrapped member so that
single increments are guaranteed and returned appropriately for
comparison with your ==.

It can be used by such a wrapper thus:

        /// Atomically pre-increment <value_>.
        WordType operator++ (void)
        {
            return Atomic::inc<WordType> ( value_ );
        }

I've attached an old bit of code that shows this wrapper with a policy
to support atomic or non atomic ops. Not quite tidy... but you'll get
the gist of what I tried to do I hope.

Hope this helps,

matt.




Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk