Debian Codegraph @

srtcore/sync.h

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2019 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 #pragma once
11 #ifndef INC_SRT_SYNC_H
12 #define INC_SRT_SYNC_H
13
14 #include "platform_sys.h"
15 #include "srt_attr_defs.h"
16
17 #include <cstdlib>
18 #include <limits>
19 #ifdef ENABLE_STDCXX_SYNC
20 #include <chrono>
21 #include <thread>
22 #include <mutex>
23 #include <condition_variable>
24 #include <atomic>
25 #if HAVE_CXX17
26 #include <shared_mutex>
27 #endif
28 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_STDCXX_STEADY
29 #define SRT_SYNC_CLOCK_STR "STDCXX_STEADY"
30 #else
31 #include <pthread.h>
32
33 // Defile clock type to use
34 #ifdef IA32
35 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_IA32_RDTSC
36 #define SRT_SYNC_CLOCK_STR "IA32_RDTSC"
37 #elif defined(IA64)
38 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_IA64_ITC
39 #define SRT_SYNC_CLOCK_STR "IA64_ITC"
40 #elif defined(AMD64)
41 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_AMD64_RDTSC
42 #define SRT_SYNC_CLOCK_STR "AMD64_RDTSC"
43 #elif defined(_WIN32)
44 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_WINQPC
45 #define SRT_SYNC_CLOCK_STR "WINQPC"
46 #elif TARGET_OS_MAC
47 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_MACH_ABSTIME
48 #define SRT_SYNC_CLOCK_STR "MACH_ABSTIME"
49 #elif defined(ENABLE_MONOTONIC_CLOCK)
50 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_GETTIME_MONOTONIC
51 #define SRT_SYNC_CLOCK_STR "GETTIME_MONOTONIC"
52 #else
53 #define SRT_SYNC_CLOCK SRT_SYNC_CLOCK_POSIX_GETTIMEOFDAY
54 #define SRT_SYNC_CLOCK_STR "POSIX_GETTIMEOFDAY"
55 #endif
56
57 #endif // ENABLE_STDCXX_SYNC
58
59 #include "srt.h"
60 #include "utilities.h"
61
62
63 namespace srt
64 {
65
66 class CUDTException; // defined in common.h
67
68 namespace sync
69 {
70
71 ///////////////////////////////////////////////////////////////////////////////
72 //
73 // Duration class
74 //
75 ///////////////////////////////////////////////////////////////////////////////
76
77 #if ENABLE_STDCXX_SYNC
78
79 template <class Clock>
80 using Duration = std::chrono::duration<Clock>;
81
82 #else
83
84 /// Class template srt::sync::Duration represents a time interval.
85 /// It consists of a count of ticks of _Clock.
86 /// It is a wrapper of system timers in case of non-C++11 chrono build.
87 template <class Clock>
88 class Duration
89 {
90 public:
91 Duration()
92 : m_duration(0)
93 {
94 }
95
96 explicit Duration(int64_t d)
97 : m_duration(d)
98 {
99 }
100
101 public:
102 inline int64_t count() const { return m_duration; }
103
104 static Duration zero() { return Duration(); }
105
106 public: // Relational operators
107 inline bool operator>=(const Duration& rhs) const { return m_duration >= rhs.m_duration; }
108 inline bool operator>(const Duration& rhs) const { return m_duration > rhs.m_duration; }
109 inline bool operator==(const Duration& rhs) const { return m_duration == rhs.m_duration; }
110 inline bool operator!=(const Duration& rhs) const { return m_duration != rhs.m_duration; }
111 inline bool operator<=(const Duration& rhs) const { return m_duration <= rhs.m_duration; }
112 inline bool operator<(const Duration& rhs) const { return m_duration < rhs.m_duration; }
113
114 public: // Assignment operators
115 inline void operator*=(const int64_t mult) { m_duration = static_cast<int64_t>(m_duration * mult); }
116 inline void operator+=(const Duration& rhs) { m_duration += rhs.m_duration; }
117 inline void operator-=(const Duration& rhs) { m_duration -= rhs.m_duration; }
118
119 inline Duration operator+(const Duration& rhs) const { return Duration(m_duration + rhs.m_duration); }
120 inline Duration operator-(const Duration& rhs) const { return Duration(m_duration - rhs.m_duration); }
121 inline Duration operator*(const int64_t& rhs) const { return Duration(m_duration * rhs); }
122 inline Duration operator/(const int64_t& rhs) const { return Duration(m_duration / rhs); }
123
124 private:
125 // int64_t range is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
126 int64_t m_duration;
127 };
128
129 #endif // ENABLE_STDCXX_SYNC
130
131 ///////////////////////////////////////////////////////////////////////////////
132 //
133 // TimePoint and steadt_clock classes
134 //
135 ///////////////////////////////////////////////////////////////////////////////
136
137 #if ENABLE_STDCXX_SYNC
138
139 using steady_clock = std::chrono::steady_clock;
140
141 template <class Clock, class Duration = typename Clock::duration>
142 using time_point = std::chrono::time_point<Clock, Duration>;
143
144 template <class Clock>
145 using TimePoint = std::chrono::time_point<Clock>;
146
147 template <class Clock, class Duration = typename Clock::duration>
148 inline bool is_zero(const time_point<Clock, Duration> &tp)
149 {
150 return tp.time_since_epoch() == Clock::duration::zero();
151 }
152
153 inline bool is_zero(const steady_clock::time_point& t)
154 {
155 return t == steady_clock::time_point();
156 }
157
158 #else
159 template <class Clock>
160 class TimePoint;
161
162 class steady_clock
163 {
164 public:
165 typedef Duration<steady_clock> duration;
166 typedef TimePoint<steady_clock> time_point;
167
168 public:
169 static time_point now();
170 };
171
172 /// Represents a point in time
173 template <class Clock>
174 class TimePoint
175 {
176 public:
177 TimePoint()
178 : m_timestamp(0)
179 {
180 }
181
182 explicit TimePoint(uint64_t tp)
183 : m_timestamp(tp)
184 {
185 }
186
187 TimePoint(const TimePoint<Clock>& other)
188 : m_timestamp(other.m_timestamp)
189 {
190 }
191
192 TimePoint(const Duration<Clock>& duration_since_epoch)
193 : m_timestamp(duration_since_epoch.count())
194 {
195 }
196
197 ~TimePoint() {}
198
199 public: // Relational operators
200 inline bool operator<(const TimePoint<Clock>& rhs) const { return m_timestamp < rhs.m_timestamp; }
201 inline bool operator<=(const TimePoint<Clock>& rhs) const { return m_timestamp <= rhs.m_timestamp; }
202 inline bool operator==(const TimePoint<Clock>& rhs) const { return m_timestamp == rhs.m_timestamp; }
203 inline bool operator!=(const TimePoint<Clock>& rhs) const { return m_timestamp != rhs.m_timestamp; }
204 inline bool operator>=(const TimePoint<Clock>& rhs) const { return m_timestamp >= rhs.m_timestamp; }
205 inline bool operator>(const TimePoint<Clock>& rhs) const { return m_timestamp > rhs.m_timestamp; }
206
207 public: // Arithmetic operators
208 inline Duration<Clock> operator-(const TimePoint<Clock>& rhs) const
209 {
210 return Duration<Clock>(m_timestamp - rhs.m_timestamp);
211 }
212 inline TimePoint operator+(const Duration<Clock>& rhs) const { return TimePoint(m_timestamp + rhs.count()); }
213 inline TimePoint operator-(const Duration<Clock>& rhs) const { return TimePoint(m_timestamp - rhs.count()); }
214
215 public: // Assignment operators
216 inline void operator=(const TimePoint<Clock>& rhs) { m_timestamp = rhs.m_timestamp; }
217 inline void operator+=(const Duration<Clock>& rhs) { m_timestamp += rhs.count(); }
218 inline void operator-=(const Duration<Clock>& rhs) { m_timestamp -= rhs.count(); }
219
220 public: //
221 static inline ATR_CONSTEXPR TimePoint min() { return TimePoint(std::numeric_limits<uint64_t>::min()); }
222 static inline ATR_CONSTEXPR TimePoint max() { return TimePoint(std::numeric_limits<uint64_t>::max()); }
223
224 public:
225 Duration<Clock> time_since_epoch() const;
226
227 private:
228 uint64_t m_timestamp;
229 };
230
231 template <>
232 srt::sync::Duration<srt::sync::steady_clock> srt::sync::TimePoint<srt::sync::steady_clock>::time_since_epoch() const;
233
234 inline Duration<steady_clock> operator*(const int& lhs, const Duration<steady_clock>& rhs)
235 {
236 return rhs * lhs;
237 }
238
239 #endif // ENABLE_STDCXX_SYNC
240
241 // NOTE: Moved the following class definitions to "atomic_clock.h"
242 // template <class Clock>
243 // class AtomicDuration;
244 // template <class Clock>
245 // class AtomicClock;
246
247 ///////////////////////////////////////////////////////////////////////////////
248 //
249 // Duration and timepoint conversions
250 //
251 ///////////////////////////////////////////////////////////////////////////////
252
253 /// Function return number of decimals in a subsecond precision.
254 /// E.g. for a microsecond accuracy of steady_clock the return would be 6.
255 /// For a nanosecond accuracy of the steady_clock the return value would be 9.
256 int clockSubsecondPrecision();
257
258 #if ENABLE_STDCXX_SYNC
259
260 inline long long count_microseconds(const steady_clock::duration &t)
261 {
262 return std::chrono::duration_cast<std::chrono::microseconds>(t).count();
263 }
264
265 inline long long count_microseconds(const steady_clock::time_point tp)
266 {
267 return std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count();
268 }
269
270 inline long long count_milliseconds(const steady_clock::duration &t)
271 {
272 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
273 }
274
275 inline long long count_seconds(const steady_clock::duration &t)
276 {
277 return std::chrono::duration_cast<std::chrono::seconds>(t).count();
278 }
279
280 inline steady_clock::duration microseconds_from(int64_t t_us)
281 {
282 return std::chrono::microseconds(t_us);
283 }
284
285 inline steady_clock::duration milliseconds_from(int64_t t_ms)
286 {
287 return std::chrono::milliseconds(t_ms);
288 }
289
290 inline steady_clock::duration seconds_from(int64_t t_s)
291 {
292 return std::chrono::seconds(t_s);
293 }
294
295 #else
296
297 int64_t count_microseconds(const steady_clock::duration& t);
298 int64_t count_milliseconds(const steady_clock::duration& t);
299 int64_t count_seconds(const steady_clock::duration& t);
300
301 Duration<steady_clock> microseconds_from(int64_t t_us);
302 Duration<steady_clock> milliseconds_from(int64_t t_ms);
303 Duration<steady_clock> seconds_from(int64_t t_s);
304
305 inline bool is_zero(const TimePoint<steady_clock>& t)
306 {
307 return t == TimePoint<steady_clock>();
308 }
309
310 #endif // ENABLE_STDCXX_SYNC
311
312
313 ///////////////////////////////////////////////////////////////////////////////
314 //
315 // Mutex section
316 //
317 ///////////////////////////////////////////////////////////////////////////////
318
319 #if ENABLE_STDCXX_SYNC
320 using Mutex = std::mutex;
321 using UniqueLock = std::unique_lock<std::mutex>;
322 using ScopedLock = std::lock_guard<std::mutex>;
323 #else
324 /// Mutex is a class wrapper, that should mimic the std::chrono::mutex class.
325 /// At the moment the extra function ref() is temporally added to allow calls
326 /// to pthread_cond_timedwait(). Will be removed by introducing CEvent.
327 class SRT_ATTR_CAPABILITY("mutex") Mutex
328 {
329 friend class SyncEvent;
330
331 public:
332 Mutex();
333 ~Mutex();
334
335 public:
336 int lock() SRT_ATTR_ACQUIRE();
337 int unlock() SRT_ATTR_RELEASE();
338
339 /// @return true if the lock was acquired successfully, otherwise false
340 bool try_lock() SRT_ATTR_TRY_ACQUIRE(true);
341
342 // TODO: To be removed with introduction of the CEvent.
343 pthread_mutex_t& ref() { return m_mutex; }
344
345 private:
346 pthread_mutex_t m_mutex;
347 };
348
349 /// A pthread version of std::scoped_lock (or lock_guard for C++11).
350 class SRT_ATTR_SCOPED_CAPABILITY ScopedLock
351 {
352 public:
353 SRT_ATTR_ACQUIRE(m)
354 explicit ScopedLock(Mutex& m)
355 : m_mutex(m)
356 {
357 m_mutex.lock();
358 }
359
360 SRT_ATTR_RELEASE()
361 ~ScopedLock() { m_mutex.unlock(); }
362
363 private:
364 Mutex& m_mutex;
365 };
366
367 /// A pthread version of std::chrono::unique_lock<mutex>
368 class SRT_ATTR_SCOPED_CAPABILITY UniqueLock
369 {
370 friend class SyncEvent;
371 int m_iLocked;
372 Mutex& m_Mutex;
373
374 public:
375 SRT_ATTR_ACQUIRE(m)
376 explicit UniqueLock(Mutex &m);
377
378 SRT_ATTR_RELEASE()
379 ~UniqueLock();
380
381 public:
382 SRT_ATTR_ACQUIRE()
383 void lock();
384
385 SRT_ATTR_RELEASE()
386 void unlock();
387
388 SRT_ATTR_RETURN_CAPABILITY(m_Mutex)
389 Mutex* mutex(); // reflects C++11 unique_lock::mutex()
390 };
391 #endif // ENABLE_STDCXX_SYNC
392
393 inline void enterCS(Mutex& m) SRT_ATTR_EXCLUDES(m) SRT_ATTR_ACQUIRE(m) { m.lock(); }
394
395 inline bool tryEnterCS(Mutex& m) SRT_ATTR_EXCLUDES(m) SRT_ATTR_TRY_ACQUIRE(true, m) { return m.try_lock(); }
396
397 inline void leaveCS(Mutex& m) SRT_ATTR_REQUIRES(m) SRT_ATTR_RELEASE(m) { m.unlock(); }
398
399 class InvertedLock
400 {
401 Mutex& m_mtx;
402
403 public:
404 SRT_ATTR_REQUIRES(m) SRT_ATTR_RELEASE(m)
405 InvertedLock(Mutex& m)
406 : m_mtx(m)
407 {
408 m_mtx.unlock();
409 }
410
411 SRT_ATTR_ACQUIRE(m_mtx)
412 ~InvertedLock()
413 {
414 m_mtx.lock();
415 }
416 };
417
418 inline void setupMutex(Mutex&, const char*) {}
419 inline void releaseMutex(Mutex&) {}
420
421 ////////////////////////////////////////////////////////////////////////////////
422 //
423 // Condition section
424 //
425 ////////////////////////////////////////////////////////////////////////////////
426
427 class Condition
428 {
429 public:
430 Condition();
431 ~Condition();
432 public:
433 /// These functions do not align with C++11 version. They are here hopefully as a temporal solution
434 /// to avoid issues with static initialization of CV on windows.
435 void init();
436 void reset();
437 void destroy();
438
439 public:
440 /// Causes the current thread to block until the condition variable is notified
441 /// or a spurious wakeup occurs.
442 ///
443 /// @param lock Corresponding mutex locked by UniqueLock
444 void wait(UniqueLock& lock);
445
446 /// Atomically releases lock, blocks the current executing thread,
447 /// and adds it to the list of threads waiting on *this.
448 /// The thread will be unblocked when notify_all() or notify_one() is executed,
449 /// or when the relative timeout rel_time expires.
450 /// It may also be unblocked spuriously. When unblocked, regardless of the reason,
451 /// lock is reacquired and wait_for() exits.
452 ///
453 /// @returns false if the relative timeout specified by rel_time expired,
454 /// true otherwise (signal or spurious wake up).
455 ///
456 /// @note Calling this function if lock.mutex()
457 /// is not locked by the current thread is undefined behavior.
458 /// Calling this function if lock.mutex() is not the same mutex as the one
459 /// used by all other threads that are currently waiting on the same
460 /// condition variable is undefined behavior.
461 bool wait_for(UniqueLock& lock, const steady_clock::duration& rel_time);
462
463 /// Causes the current thread to block until the condition variable is notified,
464 /// a specific time is reached, or a spurious wakeup occurs.
465 ///
466 /// @param[in] lock an object of type UniqueLock, which must be locked by the current thread
467 /// @param[in] timeout_time an object of type time_point representing the time when to stop waiting
468 ///
469 /// @returns false if the relative timeout specified by timeout_time expired,
470 /// true otherwise (signal or spurious wake up).
471 bool wait_until(UniqueLock& lock, const steady_clock::time_point& timeout_time);
472
473 /// Calling notify_one() unblocks one of the waiting threads,
474 /// if any threads are waiting on this CV.
475 void notify_one();
476
477 /// Unblocks all threads currently waiting for this CV.
478 void notify_all();
479
480 private:
481 #if ENABLE_STDCXX_SYNC
482 std::condition_variable m_cv;
483 #else
484 pthread_cond_t m_cv;
485 #endif
486 };
487
488 inline void setupCond(Condition& cv, const char*) { cv.init(); }
489 inline void resetCond(Condition& cv) { cv.reset(); }
490 inline void releaseCond(Condition& cv) { cv.destroy(); }
491
492 ///////////////////////////////////////////////////////////////////////////////
493 //
494 // Shared Mutex section
495 //
496 ///////////////////////////////////////////////////////////////////////////////
497
498 #if defined(ENABLE_STDCXX_SYNC) && HAVE_CXX17
499 using SharedMutex = std::shared_mutex;
500 #else
501
502 /// Implementation of a read-write mutex.
503 /// This allows multiple readers at a time, or a single writer.
504 /// TODO: The class can be improved if needed to give writer a preference
505 /// by adding additional m_iWritersWaiting member variable (counter).
506 /// TODO: The m_iCountRead could be made atomic to make unlock_shared() faster and lock-free.
507 class SharedMutex
508 {
509 public:
510 SharedMutex();
511 ~SharedMutex();
512
513 public:
514 /// Acquire the lock for writing purposes. Only one thread can acquire this lock at a time
515 /// Once it is locked, no reader can acquire it
516 void lock();
517 bool try_lock();
518 void unlock();
519
520 /// Acquire the lock if no writer already has it. For read purpose only
521 /// Several readers can lock this at the same time.
522 void lock_shared();
523 bool try_lock_shared();
524 void unlock_shared();
525
526 int getReaderCount() const;
527
528 protected:
529 Condition m_LockWriteCond;
530 Condition m_LockReadCond;
531
532 mutable Mutex m_Mutex;
533
534 int m_iCountRead;
535 bool m_bWriterLocked;
536 };
537 #endif
538
539 inline void enterCS(SharedMutex& m) SRT_ATTR_EXCLUDES(m) SRT_ATTR_ACQUIRE(m) { m.lock(); }
540
541 inline bool tryEnterCS(SharedMutex& m) SRT_ATTR_EXCLUDES(m) SRT_ATTR_TRY_ACQUIRE(true, m) { return m.try_lock(); }
542
543 inline void leaveCS(SharedMutex& m) SRT_ATTR_REQUIRES(m) SRT_ATTR_RELEASE(m) { m.unlock(); }
544
545 inline void setupMutex(SharedMutex&, const char*) {}
546 inline void releaseMutex(SharedMutex&) {}
547
548 /// A version of std::scoped_lock<std::shared_mutex> (or lock_guard for C++11).
549 /// We could have used the srt::sync::ScopedLock making it a template-based class.
550 /// But in that case all usages would have to be specified like ScopedLock<Mutex> in C++03.
551 class SRT_ATTR_SCOPED_CAPABILITY ExclusiveLock
552 {
553 public:
554 SRT_ATTR_ACQUIRE(m)
555 explicit ExclusiveLock(SharedMutex& m)
556 : m_mutex(m)
557 {
558 m_mutex.lock();
559 }
560
561 SRT_ATTR_RELEASE(m_mutex)
562 ~ExclusiveLock() { m_mutex.unlock(); }
563
564 private:
565 SharedMutex& m_mutex;
566 };
567
568 /// A reduced implementation of the std::shared_lock functionality (available in C++14).
569 class SRT_ATTR_SCOPED_CAPABILITY SharedLock
570 {
571 public:
572 SRT_ATTR_ACQUIRE_SHARED(m)
573 explicit SharedLock(SharedMutex& m)
574 : m_mtx(m)
575 {
576 m_mtx.lock_shared();
577 }
578
579 SRT_ATTR_RELEASE_SHARED(m_mtx)
580 ~SharedLock() { m_mtx.unlock_shared(); }
581
582 private:
583 SharedMutex& m_mtx;
584 };
585
586 /// A class template for a shared object. It is a wrapper around a pointer to an object
587 /// and a shared mutex. It allows multiple readers to access the object at the same time,
588 /// but only one writer can access the object at a time.
589 template <class T>
590 class CSharedObjectPtr : public SharedMutex
591 {
592 public:
593 CSharedObjectPtr()
594 : m_pObj(NULL)
595 {
596 }
597
598 bool compare_exchange(T* expected, T* newobj)
599 {
600 ExclusiveLock lock(*this);
601 if (m_pObj != expected)
602 return false;
603 m_pObj = newobj;
604 return true;
605 }
606
607 T* get_locked(SharedLock& /*wholocked*/)
608 {
609 // XXX Here you can assert that `wholocked` locked *this.
610 return m_pObj;
611 }
612
613 private:
614 T* m_pObj;
615 };
616
617 ///////////////////////////////////////////////////////////////////////////////
618 //
619 // Event (CV) section
620 //
621 ///////////////////////////////////////////////////////////////////////////////
622
623 // This class is used for condition variable combined with mutex by different ways.
624 // This should provide a cleaner API around locking with debug-logging inside.
625 class CSync
626 {
627 protected:
628 Condition* m_cond;
629 UniqueLock* m_locker;
630
631 public:
632 // Locked version: must be declared only after the declaration of UniqueLock,
633 // which has locked the mutex. On this delegate you should call only
634 // signal_locked() and pass the UniqueLock variable that should remain locked.
635 // Also wait() and wait_for() can be used only with this socket.
636 CSync(Condition& cond, UniqueLock& g)
637 : m_cond(&cond), m_locker(&g)
638 {
639 // XXX it would be nice to check whether the owner is also current thread
640 // but this can't be done portable way.
641
642 // When constructed by this constructor, the user is expected
643 // to only call signal_locked() function. You should pass the same guard
644 // variable that you have used for construction as its argument.
645 }
646
647 // COPY CONSTRUCTOR: DEFAULT!
648
649 // Wait indefinitely, until getting a signal on CV.
650 void wait()
651 {
652 m_cond->wait(*m_locker);
653 }
654
655 /// Block the call until either @a timestamp time achieved
656 /// or the conditional is signaled.
657 /// @param [in] delay Maximum time to wait since the moment of the call
658 /// @retval false if the relative timeout specified by rel_time expired,
659 /// @retval true if condition is signaled or spurious wake up.
660 bool wait_for(const steady_clock::duration& delay)
661 {
662 return m_cond->wait_for(*m_locker, delay);
663 }
664
665 // Wait until the given time is achieved.
666 /// @param [in] exptime The target time to wait until.
667 /// @retval false if the target wait time is reached.
668 /// @retval true if condition is signal or spurious wake up.
669 bool wait_until(const steady_clock::time_point& exptime)
670 {
671 return m_cond->wait_until(*m_locker, exptime);
672 }
673
674 // Static ad-hoc version
675 static void lock_notify_one(Condition& cond, Mutex& m)
676 {
677 ScopedLock lk(m); // XXX with thread logging, don't use ScopedLock directly!
678 cond.notify_one();
679 }
680
681 static void lock_notify_all(Condition& cond, Mutex& m)
682 {
683 ScopedLock lk(m); // XXX with thread logging, don't use ScopedLock directly!
684 cond.notify_all();
685 }
686
687 void notify_one_locked(UniqueLock& lk SRT_ATR_UNUSED)
688 {
689 // EXPECTED: lk.mutex() is LOCKED.
690 m_cond->notify_one();
691 }
692
693 void notify_all_locked(UniqueLock& lk SRT_ATR_UNUSED)
694 {
695 // EXPECTED: lk.mutex() is LOCKED.
696 m_cond->notify_all();
697 }
698
699 // The *_relaxed functions are to be used in case when you don't care
700 // whether the associated mutex is locked or not (you accept the case that
701 // a mutex isn't locked and the condition notification gets effectively
702 // missed), or you somehow know that the mutex is locked, but you don't
703 // have access to the associated UniqueLock object. This function, although
704 // it does the same thing as CSync::notify_one_locked etc. here for the
705 // user to declare explicitly that notifying is done without being
706 // prematurely certain that the associated mutex is locked.
707 //
708 // It is then expected that whenever these functions are used, an extra
709 // comment is provided to explain, why the use of the relaxed notification
710 // is correctly used.
711
712 void notify_one_relaxed() { notify_one_relaxed(*m_cond); }
713 static void notify_one_relaxed(Condition& cond) { cond.notify_one(); }
714 static void notify_all_relaxed(Condition& cond) { cond.notify_all(); }
715 };
716
717 ////////////////////////////////////////////////////////////////////////////////
718 //
719 // CEvent class
720 //
721 ////////////////////////////////////////////////////////////////////////////////
722
723 // XXX Do not use this class now, there's an unknown issue
724 // connected to object management with the use of release* functions.
725 // Until this is solved, stay with separate *Cond and *Lock fields.
726 class CEvent
727 {
728 public:
729 CEvent();
730 ~CEvent();
731
732 public:
733 Mutex& mutex() { return m_lock; }
734 Condition& cond() { return m_cond; }
735
736 public:
737 /// Causes the current thread to block until
738 /// a specific time is reached.
739 ///
740 /// @return true if condition occurred or spuriously woken up
741 /// false on timeout
742 bool lock_wait_until(const steady_clock::time_point& tp);
743
744 /// Blocks the current executing thread,
745 /// and adds it to the list of threads waiting on* this.
746 /// The thread will be unblocked when notify_all() or notify_one() is executed,
747 /// or when the relative timeout rel_time expires.
748 /// It may also be unblocked spuriously.
749 /// Uses internal mutex to lock.
750 ///
751 /// @return true if condition occurred or spuriously woken up
752 /// false on timeout
753 bool lock_wait_for(const steady_clock::duration& rel_time);
754
755 /// Atomically releases lock, blocks the current executing thread,
756 /// and adds it to the list of threads waiting on* this.
757 /// The thread will be unblocked when notify_all() or notify_one() is executed,
758 /// or when the relative timeout rel_time expires.
759 /// It may also be unblocked spuriously.
760 /// When unblocked, regardless of the reason, lock is reacquiredand wait_for() exits.
761 ///
762 /// @return true if condition occurred or spuriously woken up
763 /// false on timeout
764 bool wait_for(UniqueLock& lk, const steady_clock::duration& rel_time);
765
766 void lock_wait();
767
768 void wait(UniqueLock& lk);
769
770 void notify_one();
771
772 void notify_all();
773
774 void lock_notify_one()
775 {
776 ScopedLock lk(m_lock); // XXX with thread logging, don't use ScopedLock directly!
777 m_cond.notify_one();
778 }
779
780 void lock_notify_all()
781 {
782 ScopedLock lk(m_lock); // XXX with thread logging, don't use ScopedLock directly!
783 m_cond.notify_all();
784 }
785
786 private:
787 Mutex m_lock;
788 Condition m_cond;
789 };
790
791
792 // This class binds together the functionality of
793 // UniqueLock and CSync. It provides a simple interface of CSync
794 // while having already the UniqueLock applied in the scope,
795 // so a safe statement can be made about the mutex being locked
796 // when signalling or waiting.
797 class CUniqueSync: public CSync
798 {
799 UniqueLock m_ulock;
800
801 public:
802
803 UniqueLock& locker() { return m_ulock; }
804
805 SRT_ATTR_ACQUIRE(this->m_ulock.mutex())
806 CUniqueSync(Mutex& mut, Condition& cnd)
807 : CSync(cnd, m_ulock)
808 , m_ulock(mut)
809 {
810 }
811
812 CUniqueSync(CEvent& event)
813 : CSync(event.cond(), m_ulock)
814 , m_ulock(event.mutex())
815 {
816 }
817
818 SRT_ATTR_RELEASE(this->m_ulock.mutex())
819 ~CUniqueSync() {}
820
821 // These functions can be used safely because
822 // this whole class guarantees that whatever happens
823 // while its object exists is that the mutex is locked.
824
825 void notify_one()
826 {
827 m_cond->notify_one();
828 }
829
830 void notify_all()
831 {
832 m_cond->notify_all();
833 }
834 };
835
836 class CTimer
837 {
838 public:
839 CTimer();
840 ~CTimer();
841
842 public:
843 /// Causes the current thread to block until
844 /// the specified time is reached.
845 /// Sleep can be interrupted by calling interrupt()
846 /// or woken up to recheck the scheduled time by tick()
847 /// @param tp target time to sleep until
848 ///
849 /// @return true if the specified time was reached
850 /// false should never happen
851 bool sleep_until(steady_clock::time_point tp);
852
853 /// Resets target wait time and interrupts waiting
854 /// in sleep_until(..)
855 void interrupt();
856
857 /// Wakes up waiting thread (sleep_until(..)) without
858 /// changing the target waiting time to force a recheck
859 /// of the current time in comparison to the target time.
860 void tick();
861
862 private:
863 CEvent m_event;
864 steady_clock::time_point m_tsSchedTime;
865 };
866
867
868 /// Print steady clock timepoint in a human readable way.
869 /// days HH:MM:SS.us [STD]
870 /// Example: 1D 02:12:56.123456
871 ///
872 /// @param [in] steady clock timepoint
873 /// @returns a string with a formatted time representation
874 std::string FormatTime(const steady_clock::time_point& time);
875
876 /// Print steady clock timepoint relative to the current system time
877 /// Date HH:MM:SS.us [SYS]
878 /// @param [in] steady clock timepoint
879 /// @returns a string with a formatted time representation
880 std::string FormatTimeSys(const steady_clock::time_point& time);
881
882 enum eDurationUnit {DUNIT_S, DUNIT_MS, DUNIT_US};
883
884 template <eDurationUnit u>
885 struct DurationUnitName;
886
887 template<>
888 struct DurationUnitName<DUNIT_US>
889 {
890 static const char* name() { return "us"; }
891 static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur)); }
892 };
893
894 template<>
895 struct DurationUnitName<DUNIT_MS>
896 {
897 static const char* name() { return "ms"; }
898 static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur))/1000.0; }
899 };
900
901 template<>
902 struct DurationUnitName<DUNIT_S>
903 {
904 static const char* name() { return "s"; }
905 static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur))/1000000.0; }
906 };
907
908 template<eDurationUnit UNIT>
909 inline std::string FormatDuration(const steady_clock::duration& dur)
910 {
911 return Sprint(std::fixed, DurationUnitName<UNIT>::count(dur)) + DurationUnitName<UNIT>::name();
912 }
913
914 inline std::string FormatDuration(const steady_clock::duration& dur)
915 {
916 return FormatDuration<DUNIT_US>(dur);
917 }
918
919 ////////////////////////////////////////////////////////////////////////////////
920 //
921 // CGlobEvent class
922 //
923 ////////////////////////////////////////////////////////////////////////////////
924
925 class CGlobEvent
926 {
927 public:
928 /// Triggers the event and notifies waiting threads.
929 /// Simply calls notify_one().
930 static void triggerEvent();
931
932 /// Waits for the event to be triggered with 10ms timeout.
933 /// Simply calls wait_for().
934 static bool waitForEvent();
935 };
936
937 ////////////////////////////////////////////////////////////////////////////////
938 //
939 // CThread class
940 //
941 ////////////////////////////////////////////////////////////////////////////////
942
943 #ifdef ENABLE_STDCXX_SYNC
944 typedef std::system_error CThreadException;
945 using CThread = std::thread;
946 namespace this_thread = std::this_thread;
947 #else // pthreads wrapper version
948 typedef CUDTException CThreadException;
949
950 class CThread
951 {
952 public:
953 CThread();
954 /// @throws std::system_error if the thread could not be started.
955 CThread(void *(*start_routine) (void *), void *arg);
956
957 #if HAVE_FULL_CXX11
958 CThread& operator=(CThread &other) = delete;
959 CThread& operator=(CThread &&other);
960 #else
961 CThread& operator=(CThread &other);
962 /// To be used only in StartThread function.
963 /// Creates a new stread and assigns to this.
964 /// @throw CThreadException
965 void create_thread(void *(*start_routine) (void *), void *arg);
966 #endif
967
968 public: // Observers
969 /// Checks if the CThread object identifies an active thread of execution.
970 /// A default constructed thread is not joinable.
971 /// A thread that has finished executing code, but has not yet been joined
972 /// is still considered an active thread of execution and is therefore joinable.
973 bool joinable() const;
974
975 struct id
976 {
977 explicit id(const pthread_t t)
978 : value(t)
979 {}
980
981 const pthread_t value;
982 inline bool operator==(const id& second) const
983 {
984 return pthread_equal(value, second.value) != 0;
985 }
986 };
987
988 /// Returns the id of the current thread.
989 /// In this implementation the ID is the pthread_t.
990 const id get_id() const { return id(m_thread); }
991
992 public:
993 /// Blocks the current thread until the thread identified by *this finishes its execution.
994 /// If that thread has already terminated, then join() returns immediately.
995 ///
996 /// @throws std::system_error if an error occurs
997 void join();
998
999 public: // Internal
1000 /// Calls pthread_create, throws exception on failure.
1001 /// @throw CThreadException
1002 void create(void *(*start_routine) (void *), void *arg);
1003
1004 private:
1005 pthread_t m_thread;
1006 pid_t m_pid;
1007 };
1008
1009 template <class Stream>
1010 inline Stream& operator<<(Stream& str, const CThread::id& cid)
1011 {
1012 #if defined(_WIN32) && (defined(PTW32_VERSION) || defined (__PTW32_VERSION))
1013 // This is a version specific for pthread-win32 implementation
1014 // Here pthread_t type is a structure that is not convertible
1015 // to a number at all.
1016 return str << pthread_getw32threadid_np(cid.value);
1017 #else
1018 return str << cid.value;
1019 #endif
1020 }
1021
1022 namespace this_thread
1023 {
1024 const inline CThread::id get_id() { return CThread::id (pthread_self()); }
1025
1026 inline void sleep_for(const steady_clock::duration& t)
1027 {
1028 #if !defined(_WIN32)
1029 usleep(count_microseconds(t)); // microseconds
1030 #else
1031 Sleep((DWORD) count_milliseconds(t));
1032 #endif
1033 }
1034 }
1035
1036 #endif
1037
1038 inline void resetThread(CThread* th) { (void)new (th) CThread; }
1039
1040 /// StartThread function should be used to do CThread assignments:
1041 /// @code
1042 /// CThread a();
1043 /// a = CThread(func, args);
1044 /// @endcode
1045 ///
1046 /// @returns true if thread was started successfully,
1047 /// false on failure
1048 ///
1049 #ifdef ENABLE_STDCXX_SYNC
1050 typedef void* (&ThreadFunc) (void*);
1051 bool StartThread(CThread& th, ThreadFunc&& f, void* args, const std::string& name);
1052 #else
1053 bool StartThread(CThread& th, void* (*f) (void*), void* args, const std::string& name);
1054 #endif
1055
1056 ////////////////////////////////////////////////////////////////////////////////
1057 //
1058 // CThreadError class - thread local storage wrapper
1059 //
1060 ////////////////////////////////////////////////////////////////////////////////
1061
1062 /// Set thread local error
1063 /// @param e new CUDTException
1064 void SetThreadLocalError(const CUDTException& e);
1065
1066 /// Get thread local error
1067 /// @returns CUDTException pointer
1068 CUDTException& GetThreadLocalError();
1069
1070 ////////////////////////////////////////////////////////////////////////////////
1071 //
1072 // Random distribution functions.
1073 //
1074 ////////////////////////////////////////////////////////////////////////////////
1075
1076 /// Generate a uniform-distributed random integer from [minVal; maxVal].
1077 /// If HAVE_CXX11, uses std::uniform_distribution(std::random_device).
1078 /// @param[in] minVal minimum allowed value of the resulting random number.
1079 /// @param[in] maxVal maximum allowed value of the resulting random number.
1080 int genRandomInt(int minVal, int maxVal);
1081
1082 } // namespace sync
1083 } // namespace srt
1084
1085 #include "atomic_clock.h"
1086
1087 #endif // INC_SRT_SYNC_H