###  | # Boost.Threads ## atomic_t

## Header

The `atomic_t` class defines an "atomic integer" type. This class should be used to perform thread safe operations on an integral type with out the overhead of locks. Only a limited set of integer operations are available with an `atomic_t` instance.

    #include <boost/thread/atomic.hpp>

## Public Interface

        class atomic_t
        {
        public:
           typedef implementation defined value_type;

           explicit atomic_t(value_type val=0);
        };

        atomic_t::value_type read(const atomic_t& x);
        atomic_t::value_type increment(atomic_t& x);
        atomic_t::value_type decrement(atomic_t& x);
        atomic_t::value_type swap(atomic_t& x, atomic_t::value_type y);
        atomic_t::value_type compare_swap(atomic_t& x, atomic_t::value_type y, atomic_t::value_type z);

### Constructor

        atomic_t(atomic_t::value_type val=0);

Constructs an `atomic_t` and sets its value to `val`.

### read

         atomic_t::value_type read(const atomic_t& x);

Gets the current value of `x`.

### increment

        atomic_t::value_type increment(atomic_t& x);

Increments `x` and returns a value `< 0` if the result is less than 0, `> 0` if the result is greater than 0 and `== 0` if the result is equal to 0.

### decrement

        atomic_t::value_type decrement(atomic_t& x);

Decrements `x` and returns a value `< 0` if the result is less than 0, `> 0` if the result is greater than 0 and `== 0` if the result is equal to 0.

### swap

        atomic_t::value_type swap(atomic_t& x, atomic_t::value_type y);

Assigns the value of `y` to `x` and returns the value of `x` prior to the swap.

### compare_swap

        atomic_t::value_type compare_swap(atomic_t& x, atomic_t::value_type y, atomic_t::value_type z);

Compares the value of `z` to the value of `x` and if equal sets the value of `x` to the value of `y` and returns the value of `x` prior to the swap.

## Example Usage

    #include <boost/thread/atomic.hpp>
    #include <boost/test/test_tools.hpp>

    int test_main(int, char*[])
    {
        boost::atomic_t a;
        BOOST_TEST_VERIFY(boost::read(a) == 0);
        BOOST_TEST_VERIFY(boost::increment(a) > 0);
        BOOST_TEST_VERIFY(boost::decrement(a) == 0);
        BOOST_TEST_VERIFY(boost::swap(a, 1) == 0);
        BOOST_TEST_VERIFY(boost::swap(a, 2, 0) == 1);
        BOOST_TEST_VERIFY(boost::read(a) == 1);
    }

Revised 01 October, 2001

© Copyright William E. Kempf 2001 all rights reserved.