1 /* 2 * SRT - Secure, Reliable, Transport 3 * Copyright (c) 2021 Haivision Systems Inc. 4 * 5 * This Source Code Form is subject to the terms of the Mozilla Public 6 * License, v. 2.0. If a copy of the MPL was not distributed with this 7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. 8 * 9 */ 10 11 #ifndef INC_SRT_SYNC_ATOMIC_CLOCK_H 12 #define INC_SRT_SYNC_ATOMIC_CLOCK_H 13 14 #include "sync.h" 15 #include "atomic.h" 16 17 namespace srt 18 { 19 namespace sync 20 { 21 22 template <class Clock> 23 class AtomicDuration 24 { 25 atomic<int64_t> dur; 26 typedef typename Clock::duration duration_type; 27 typedef typename Clock::time_point time_point_type; 28 public: 29 AtomicDuration()30 AtomicDuration() ATR_NOEXCEPT : dur(0) {} 31 load()32 duration_type load() 33 { 34 int64_t val = dur.load(); 35 return duration_type(val); 36 } 37 store(const duration_type & d)38 void store(const duration_type& d) 39 { 40 dur.store(d.count()); 41 } 42 43 AtomicDuration<Clock>& operator=(const duration_type& s) 44 { 45 dur = s.count(); 46 return *this; 47 } 48 duration_type()49 operator duration_type() const 50 { 51 return duration_type(dur); 52 } 53 }; 54 55 template <class Clock> 56 class AtomicClock 57 { 58 atomic<uint64_t> dur; 59 typedef typename Clock::duration duration_type; 60 typedef typename Clock::time_point time_point_type; 61 public: 62 AtomicClock()63 AtomicClock() ATR_NOEXCEPT : dur(0) {} 64 load()65 time_point_type load() const 66 { 67 int64_t val = dur.load(); 68 return time_point_type(duration_type(val)); 69 } 70 store(const time_point_type & d)71 void store(const time_point_type& d) 72 { 73 dur.store(uint64_t(d.time_since_epoch().count())); 74 } 75 76 AtomicClock& operator=(const time_point_type& s) 77 { 78 dur = s.time_since_epoch().count(); 79 return *this; 80 } 81 time_point_type()82 operator time_point_type() const 83 { 84 return time_point_type(duration_type(dur.load())); 85 } 86 }; 87 88 } // namespace sync 89 } // namespace srt 90 91 #endif // INC_SRT_SYNC_ATOMIC_CLOCK_H 92