2013-10-28 12:48:13 -07:00
|
|
|
#ifndef AL_ATOMIC_H
|
|
|
|
#define AL_ATOMIC_H
|
|
|
|
|
2018-11-17 18:56:00 -08:00
|
|
|
#include <atomic>
|
|
|
|
|
2018-01-11 10:03:26 -08:00
|
|
|
|
2018-11-19 02:17:06 -08:00
|
|
|
using RefCount = std::atomic<unsigned int>;
|
2014-07-22 18:18:14 -07:00
|
|
|
|
2019-08-01 13:28:53 -07:00
|
|
|
inline void InitRef(RefCount &ref, unsigned int value)
|
|
|
|
{ ref.store(value, std::memory_order_relaxed); }
|
|
|
|
inline unsigned int ReadRef(RefCount &ref)
|
|
|
|
{ return ref.load(std::memory_order_acquire); }
|
|
|
|
inline unsigned int IncrementRef(RefCount &ref)
|
|
|
|
{ return ref.fetch_add(1u, std::memory_order_acq_rel)+1u; }
|
|
|
|
inline unsigned int DecrementRef(RefCount &ref)
|
|
|
|
{ return ref.fetch_sub(1u, std::memory_order_acq_rel)-1u; }
|
2014-07-22 18:18:14 -07:00
|
|
|
|
2014-09-03 17:37:07 -07:00
|
|
|
|
2016-12-21 19:58:03 -08:00
|
|
|
/* WARNING: A livelock is theoretically possible if another thread keeps
|
|
|
|
* changing the head without giving this a chance to actually swap in the new
|
|
|
|
* one (practically impossible with this little code, but...).
|
|
|
|
*/
|
2018-11-19 01:20:03 -08:00
|
|
|
template<typename T>
|
|
|
|
inline void AtomicReplaceHead(std::atomic<T> &head, T newhead)
|
|
|
|
{
|
|
|
|
T first_ = head.load(std::memory_order_acquire);
|
|
|
|
do {
|
|
|
|
newhead->next.store(first_, std::memory_order_relaxed);
|
|
|
|
} while(!head.compare_exchange_weak(first_, newhead,
|
|
|
|
std::memory_order_acq_rel, std::memory_order_acquire));
|
|
|
|
}
|
2016-12-21 19:58:03 -08:00
|
|
|
|
2013-10-28 12:48:13 -07:00
|
|
|
#endif /* AL_ATOMIC_H */
|