tommi@webrtc.org | e84373c | 2012-04-19 14:28:45 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | // Atomic, system independent 32-bit integer. Unless you know what you're |
| 12 | // doing, use locks instead! :-) |
| 13 | // |
| 14 | // Note: uses full memory barriers. |
| 15 | // Note: assumes 32-bit (or higher) system |
| 16 | #ifndef WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ATOMIC32_H_ |
| 17 | #define WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ATOMIC32_H_ |
| 18 | |
| 19 | #include <cstddef> |
| 20 | |
| 21 | #include "common_types.h" |
| 22 | #include "constructor_magic.h" |
| 23 | |
| 24 | namespace webrtc { |
| 25 | |
| 26 | // 32 bit atomic variable. Note that this class relies on the compiler to |
| 27 | // align the 32 bit value correctly (on a 32 bit boundary), so as long as you're |
| 28 | // not doing things like reinterpret_cast over some custom allocated memory |
| 29 | // without being careful with alignment, you should be fine. |
| 30 | class Atomic32 |
| 31 | { |
| 32 | public: |
| 33 | Atomic32(WebRtc_Word32 initialValue = 0); |
| 34 | ~Atomic32(); |
| 35 | |
| 36 | // Prefix operator! |
| 37 | WebRtc_Word32 operator++(); |
| 38 | WebRtc_Word32 operator--(); |
| 39 | |
| 40 | WebRtc_Word32 operator+=(WebRtc_Word32 value); |
| 41 | WebRtc_Word32 operator-=(WebRtc_Word32 value); |
| 42 | |
| 43 | // Sets the value atomically to newValue if the value equals compare value. |
| 44 | // The function returns true if the exchange happened. |
| 45 | bool CompareExchange(WebRtc_Word32 newValue, WebRtc_Word32 compareValue); |
| 46 | WebRtc_Word32 Value() const; |
| 47 | |
| 48 | private: |
| 49 | // Disable the + and - operator since it's unclear what these operations |
| 50 | // should do. |
| 51 | Atomic32 operator+(const Atomic32& other); |
| 52 | Atomic32 operator-(const Atomic32& other); |
| 53 | |
| 54 | // Checks if |_value| is 32bit aligned. |
| 55 | inline bool Is32bitAligned() const { |
| 56 | return (reinterpret_cast<ptrdiff_t>(&_value) & 3) == 0; |
| 57 | } |
| 58 | |
| 59 | DISALLOW_COPY_AND_ASSIGN(Atomic32); |
| 60 | |
| 61 | WebRtc_Word32 _value; |
| 62 | }; |
| 63 | } // namespace webrtc |
| 64 | |
| 65 | #endif // WEBRTC_SYSTEM_WRAPPERS_INTERFACE_ATOMIC32_H_ |