1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2019 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#pragma once
#ifndef INC_SRT_SYNC_H
#define INC_SRT_SYNC_H
//#define ENABLE_STDCXX_SYNC
//#define ENABLE_CXX17
#include <cstdlib>
#ifdef ENABLE_STDCXX_SYNC
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#else
#include <pthread.h>
#endif
#include "utilities.h"
class CUDTException; // defined in common.h
namespace srt
{
namespace sync
{
using namespace std;
///////////////////////////////////////////////////////////////////////////////
//
// Duration class
//
///////////////////////////////////////////////////////////////////////////////
#if ENABLE_STDCXX_SYNC
template <class Clock>
using Duration = chrono::duration<Clock>;
#else
/// Class template srt::sync::Duration represents a time interval.
/// It consists of a count of ticks of _Clock.
/// It is a wrapper of system timers in case of non-C++11 chrono build.
template <class Clock>
class Duration
{
public:
Duration()
: m_duration(0)
{
}
explicit Duration(int64_t d)
: m_duration(d)
{
}
public:
inline int64_t count() const { return m_duration; }
static Duration zero() { return Duration(); }
public: // Relational operators
inline bool operator>=(const Duration& rhs) const { return m_duration >= rhs.m_duration; }
inline bool operator>(const Duration& rhs) const { return m_duration > rhs.m_duration; }
inline bool operator==(const Duration& rhs) const { return m_duration == rhs.m_duration; }
inline bool operator!=(const Duration& rhs) const { return m_duration != rhs.m_duration; }
inline bool operator<=(const Duration& rhs) const { return m_duration <= rhs.m_duration; }
inline bool operator<(const Duration& rhs) const { return m_duration < rhs.m_duration; }
public: // Assignment operators
inline void operator*=(const int64_t mult) { m_duration = static_cast<int64_t>(m_duration * mult); }
inline void operator+=(const Duration& rhs) { m_duration += rhs.m_duration; }
inline void operator-=(const Duration& rhs) { m_duration -= rhs.m_duration; }
inline Duration operator+(const Duration& rhs) const { return Duration(m_duration + rhs.m_duration); }
inline Duration operator-(const Duration& rhs) const { return Duration(m_duration - rhs.m_duration); }
inline Duration operator*(const int64_t& rhs) const { return Duration(m_duration * rhs); }
inline Duration operator/(const int64_t& rhs) const { return Duration(m_duration / rhs); }
private:
// int64_t range is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int64_t m_duration;
};
#endif // ENABLE_STDCXX_SYNC
///////////////////////////////////////////////////////////////////////////////
//
// TimePoint and steadt_clock classes
//
///////////////////////////////////////////////////////////////////////////////
#if ENABLE_STDCXX_SYNC
using steady_clock = chrono::steady_clock;
template <class Clock, class Duration = typename Clock::duration>
using time_point = chrono::time_point<Clock, Duration>;
template <class Clock>
using TimePoint = chrono::time_point<Clock>;
template <class Clock, class Duration = typename Clock::duration>
inline bool is_zero(const time_point<Clock, Duration> &tp)
{
return tp.time_since_epoch() == Clock::duration::zero();
}
inline bool is_zero(const steady_clock::time_point& t)
{
return t == steady_clock::time_point();
}
#else
template <class Clock>
class TimePoint;
class steady_clock
{
public:
typedef Duration<steady_clock> duration;
typedef TimePoint<steady_clock> time_point;
public:
static time_point now();
};
/// Represents a point in time
template <class Clock>
class TimePoint
{
public:
TimePoint()
: m_timestamp(0)
{
}
explicit TimePoint(uint64_t tp)
: m_timestamp(tp)
{
}
TimePoint(const TimePoint<Clock>& other)
: m_timestamp(other.m_timestamp)
{
}
~TimePoint() {}
public: // Relational operators
inline bool operator<(const TimePoint<Clock>& rhs) const { return m_timestamp < rhs.m_timestamp; }
inline bool operator<=(const TimePoint<Clock>& rhs) const { return m_timestamp <= rhs.m_timestamp; }
inline bool operator==(const TimePoint<Clock>& rhs) const { return m_timestamp == rhs.m_timestamp; }
inline bool operator!=(const TimePoint<Clock>& rhs) const { return m_timestamp != rhs.m_timestamp; }
inline bool operator>=(const TimePoint<Clock>& rhs) const { return m_timestamp >= rhs.m_timestamp; }
inline bool operator>(const TimePoint<Clock>& rhs) const { return m_timestamp > rhs.m_timestamp; }
public: // Arithmetic operators
inline Duration<Clock> operator-(const TimePoint<Clock>& rhs) const
{
return Duration<Clock>(m_timestamp - rhs.m_timestamp);
}
inline TimePoint operator+(const Duration<Clock>& rhs) const { return TimePoint(m_timestamp + rhs.count()); }
inline TimePoint operator-(const Duration<Clock>& rhs) const { return TimePoint(m_timestamp - rhs.count()); }
public: // Assignment operators
inline void operator=(const TimePoint<Clock>& rhs) { m_timestamp = rhs.m_timestamp; }
inline void operator+=(const Duration<Clock>& rhs) { m_timestamp += rhs.count(); }
inline void operator-=(const Duration<Clock>& rhs) { m_timestamp -= rhs.count(); }
public: //
#if HAVE_FULL_CXX11
static inline ATR_CONSTEXPR TimePoint min() { return TimePoint(numeric_limits<uint64_t>::min()); }
static inline ATR_CONSTEXPR TimePoint max() { return TimePoint(numeric_limits<uint64_t>::max()); }
#else
#ifndef UINT64_MAX
#define UNDEF_UINT64_MAX
#define UINT64_MAX 0xffffffffffffffffULL
#endif
static inline TimePoint min() { return TimePoint(0); }
static inline TimePoint max() { return TimePoint(UINT64_MAX); }
#ifdef UNDEF_UINT64_MAX
#undef UINT64_MAX
#endif
#endif
public:
Duration<Clock> time_since_epoch() const;
private:
uint64_t m_timestamp;
};
template <>
srt::sync::Duration<srt::sync::steady_clock> srt::sync::TimePoint<srt::sync::steady_clock>::time_since_epoch() const;
inline Duration<steady_clock> operator*(const int& lhs, const Duration<steady_clock>& rhs)
{
return rhs * lhs;
}
#endif // ENABLE_STDCXX_SYNC
///////////////////////////////////////////////////////////////////////////////
//
// Duration and timepoint conversions
//
///////////////////////////////////////////////////////////////////////////////
#if ENABLE_STDCXX_SYNC
inline long long count_microseconds(const steady_clock::duration &t)
{
return std::chrono::duration_cast<std::chrono::microseconds>(t).count();
}
inline long long count_microseconds(const steady_clock::time_point tp)
{
return std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count();
}
inline long long count_milliseconds(const steady_clock::duration &t)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
}
inline long long count_seconds(const steady_clock::duration &t)
{
return std::chrono::duration_cast<std::chrono::seconds>(t).count();
}
inline steady_clock::duration microseconds_from(int64_t t_us)
{
return std::chrono::microseconds(t_us);
}
inline steady_clock::duration milliseconds_from(int64_t t_ms)
{
return std::chrono::milliseconds(t_ms);
}
inline steady_clock::duration seconds_from(int64_t t_s)
{
return std::chrono::seconds(t_s);
}
#else
int64_t count_microseconds(const steady_clock::duration& t);
int64_t count_milliseconds(const steady_clock::duration& t);
int64_t count_seconds(const steady_clock::duration& t);
Duration<steady_clock> microseconds_from(int64_t t_us);
Duration<steady_clock> milliseconds_from(int64_t t_ms);
Duration<steady_clock> seconds_from(int64_t t_s);
inline bool is_zero(const TimePoint<steady_clock>& t)
{
return t == TimePoint<steady_clock>();
}
#endif // ENABLE_STDCXX_SYNC
///////////////////////////////////////////////////////////////////////////////
//
// Mutex section
//
///////////////////////////////////////////////////////////////////////////////
#if ENABLE_STDCXX_SYNC
using Mutex = mutex;
using UniqueLock = unique_lock<mutex>;
using ScopedLock = lock_guard<mutex>;
#else
/// Mutex is a class wrapper, that should mimic the std::chrono::mutex class.
/// At the moment the extra function ref() is temporally added to allow calls
/// to pthread_cond_timedwait(). Will be removed by introducing CEvent.
class Mutex
{
friend class SyncEvent;
public:
Mutex();
~Mutex();
public:
int lock();
int unlock();
/// @return true if the lock was acquired successfully, otherwise false
bool try_lock();
// TODO: To be removed with introduction of the CEvent.
pthread_mutex_t& ref() { return m_mutex; }
private:
pthread_mutex_t m_mutex;
};
/// A pthread version of std::chrono::scoped_lock<mutex> (or lock_guard for C++11)
class ScopedLock
{
public:
ScopedLock(Mutex& m);
~ScopedLock();
private:
Mutex& m_mutex;
};
/// A pthread version of std::chrono::unique_lock<mutex>
class UniqueLock
{
friend class SyncEvent;
public:
UniqueLock(Mutex &m);
~UniqueLock();
public:
void unlock();
Mutex* mutex(); // reflects C++11 unique_lock::mutex()
private:
int m_iLocked;
Mutex& m_Mutex;
};
#endif // ENABLE_STDCXX_SYNC
inline void enterCS(Mutex& m) { m.lock(); }
inline bool tryEnterCS(Mutex& m) { return m.try_lock(); }
inline void leaveCS(Mutex& m) { m.unlock(); }
class InvertedLock
{
Mutex *m_pMutex;
public:
InvertedLock(Mutex *m)
: m_pMutex(m)
{
if (!m_pMutex)
return;
leaveCS(*m_pMutex);
}
InvertedLock(Mutex& m)
: m_pMutex(&m)
{
leaveCS(*m_pMutex);
}
~InvertedLock()
{
if (!m_pMutex)
return;
enterCS(*m_pMutex);
}
};
inline void setupMutex(Mutex&, const char*) {}
inline void releaseMutex(Mutex&) {}
////////////////////////////////////////////////////////////////////////////////
//
// Condition section
//
////////////////////////////////////////////////////////////////////////////////
class Condition
{
public:
Condition();
~Condition();
public:
/// These functions do not align with C++11 version. They are here hopefully as a temporal solution
/// to avoud issues with static initialization of CV on windows.
void init();
void destroy();
public:
/// Causes the current thread to block until the condition variable is notified
/// or a spurious wakeup occurs.
///
/// @param lock Corresponding mutex locked by UniqueLock
void wait(UniqueLock& lock);
/// Atomically releases lock, blocks the current executing thread,
/// and adds it to the list of threads waiting on *this.
/// The thread will be unblocked when notify_all() or notify_one() is executed,
/// or when the relative timeout rel_time expires.
/// It may also be unblocked spuriously. When unblocked, regardless of the reason,
/// lock is reacquired and wait_for() exits.
///
/// @returns false if the relative timeout specified by rel_time expired,
/// true otherwise (signal or spurious wake up).
///
/// @note Calling this function if lock.mutex()
/// is not locked by the current thread is undefined behavior.
/// Calling this function if lock.mutex() is not the same mutex as the one
/// used by all other threads that are currently waiting on the same
/// condition variable is undefined behavior.
bool wait_for(UniqueLock& lock, const steady_clock::duration& rel_time);
/// Causes the current thread to block until the condition variable is notified,
/// a specific time is reached, or a spurious wakeup occurs.
///
/// @param[in] lock an object of type UniqueLock, which must be locked by the current thread
/// @param[in] timeout_time an object of type time_point representing the time when to stop waiting
///
/// @returns false if the relative timeout specified by timeout_time expired,
/// true otherwise (signal or spurious wake up).
bool wait_until(UniqueLock& lock, const steady_clock::time_point& timeout_time);
/// Calling notify_one() unblocks one of the waiting threads,
/// if any threads are waiting on this CV.
void notify_one();
/// Unblocks all threads currently waiting for this CV.
void notify_all();
private:
#if ENABLE_STDCXX_SYNC
condition_variable m_cv;
#else
pthread_cond_t m_cv;
#endif
};
inline void setupCond(Condition& cv, const char*) { cv.init(); }
inline void releaseCond(Condition& cv) { cv.destroy(); }
///////////////////////////////////////////////////////////////////////////////
//
// Event (CV) section
//
///////////////////////////////////////////////////////////////////////////////
// This class is used for condition variable combined with mutex by different ways.
// This should provide a cleaner API around locking with debug-logging inside.
class CSync
{
Condition* m_cond;
UniqueLock* m_locker;
public:
// Locked version: must be declared only after the declaration of UniqueLock,
// which has locked the mutex. On this delegate you should call only
// signal_locked() and pass the UniqueLock variable that should remain locked.
// Also wait() and wait_for() can be used only with this socket.
CSync(Condition& cond, UniqueLock& g)
: m_cond(&cond), m_locker(&g)
{
// XXX it would be nice to check whether the owner is also current thread
// but this can't be done portable way.
// When constructed by this constructor, the user is expected
// to only call signal_locked() function. You should pass the same guard
// variable that you have used for construction as its argument.
}
// COPY CONSTRUCTOR: DEFAULT!
// Wait indefinitely, until getting a signal on CV.
void wait()
{
m_cond->wait(*m_locker);
}
/// Block the call until either @a timestamp time achieved
/// or the conditional is signaled.
/// @param [in] delay Maximum time to wait since the moment of the call
/// @retval true Resumed due to getting a CV signal
/// @retval false Resumed due to being past @a timestamp
bool wait_for(const steady_clock::duration& delay)
{
return m_cond->wait_for(*m_locker, delay);
}
// Wait until the given time is achieved. This actually
// refers to wait_for for the time remaining to achieve
// given time.
bool wait_until(const steady_clock::time_point& exptime)
{
// This will work regardless as to which clock is in use. The time
// should be specified as steady_clock::time_point, so there's no
// question of the timer base.
steady_clock::time_point now = steady_clock::now();
if (now >= exptime)
return false; // timeout
return wait_for(exptime - now);
}
// Static ad-hoc version
static void lock_signal(Condition& cond, Mutex& m)
{
ScopedLock lk(m); // XXX with thread logging, don't use ScopedLock directly!
cond.notify_one();
}
static void lock_broadcast(Condition& cond, Mutex& m)
{
ScopedLock lk(m); // XXX with thread logging, don't use ScopedLock directly!
cond.notify_all();
}
void signal_locked(UniqueLock& lk ATR_UNUSED)
{
// EXPECTED: lk.mutex() is LOCKED.
m_cond->notify_one();
}
// The signal_relaxed and broadcast_relaxed functions are to be used in case
// when you don't care whether the associated mutex is locked or not (you
// accept the case that a mutex isn't locked and the signal gets effectively
// missed), or you somehow know that the mutex is locked, but you don't have
// access to the associated UniqueLock object. This function, although it does
// the same thing as signal_locked() and broadcast_locked(), is here for
// the user to declare explicitly that the signal/broadcast is done without
// being prematurely certain that the associated mutex is locked.
//
// It is then expected that whenever these functions are used, an extra
// comment is provided to explain, why the use of the relaxed signaling is
// correctly used.
void signal_relaxed() { signal_relaxed(*m_cond); }
static void signal_relaxed(Condition& cond) { cond.notify_one(); }
static void broadcast_relaxed(Condition& cond) { cond.notify_all(); }
};
////////////////////////////////////////////////////////////////////////////////
//
// CEvent class
//
////////////////////////////////////////////////////////////////////////////////
class CEvent
{
public:
CEvent();
~CEvent();
public:
Mutex& mutex() { return m_lock; }
public:
/// Causes the current thread to block until
/// a specific time is reached.
///
/// @return true if condition occured or spuriously woken up
/// false on timeout
bool lock_wait_until(const steady_clock::time_point& tp);
/// Blocks the current executing thread,
/// and adds it to the list of threads waiting on* this.
/// The thread will be unblocked when notify_all() or notify_one() is executed,
/// or when the relative timeout rel_time expires.
/// It may also be unblocked spuriously.
/// Uses internal mutex to lock.
///
/// @return true if condition occured or spuriously woken up
/// false on timeout
bool lock_wait_for(const steady_clock::duration& rel_time);
/// Atomically releases lock, blocks the current executing thread,
/// and adds it to the list of threads waiting on* this.
/// The thread will be unblocked when notify_all() or notify_one() is executed,
/// or when the relative timeout rel_time expires.
/// It may also be unblocked spuriously.
/// When unblocked, regardless of the reason, lock is reacquiredand wait_for() exits.
///
/// @return true if condition occured or spuriously woken up
/// false on timeout
bool wait_for(UniqueLock& lk, const steady_clock::duration& rel_time);
void lock_wait();
void wait(UniqueLock& lk);
void notify_one();
void notify_all();
private:
Mutex m_lock;
Condition m_cond;
};
class CTimer
{
public:
CTimer();
~CTimer();
public:
/// Causes the current thread to block until
/// the specified time is reached.
/// Sleep can be interrupted by calling interrupt()
/// or woken up to recheck the scheduled time by tick()
/// @param tp target time to sleep until
///
/// @return true if the specified time was reached
/// false should never happen
bool sleep_until(steady_clock::time_point tp);
/// Resets target wait time and interrupts waiting
/// in sleep_until(..)
void interrupt();
/// Wakes up waiting thread (sleep_until(..)) without
/// changing the target waiting time to force a recheck
/// of the current time in comparisson to the target time.
void tick();
private:
CEvent m_event;
steady_clock::time_point m_tsSchedTime;
};
/// Print steady clock timepoint in a human readable way.
/// days HH:MM::SS.us [STD]
/// Example: 1D 02:12:56.123456
///
/// @param [in] steady clock timepoint
/// @returns a string with a formatted time representation
std::string FormatTime(const steady_clock::time_point& time);
/// Print steady clock timepoint relative to the current system time
/// Date HH:MM::SS.us [SYS]
/// @param [in] steady clock timepoint
/// @returns a string with a formatted time representation
std::string FormatTimeSys(const steady_clock::time_point& time);
enum eDurationUnit {DUNIT_S, DUNIT_MS, DUNIT_US};
template <eDurationUnit u>
struct DurationUnitName;
template<>
struct DurationUnitName<DUNIT_US>
{
static const char* name() { return "us"; }
static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur)); }
};
template<>
struct DurationUnitName<DUNIT_MS>
{
static const char* name() { return "ms"; }
static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur))/1000.0; }
};
template<>
struct DurationUnitName<DUNIT_S>
{
static const char* name() { return "s"; }
static double count(const steady_clock::duration& dur) { return static_cast<double>(count_microseconds(dur))/1000000.0; }
};
template<eDurationUnit UNIT>
inline std::string FormatDuration(const steady_clock::duration& dur)
{
return Sprint(DurationUnitName<UNIT>::count(dur)) + DurationUnitName<UNIT>::name();
}
inline std::string FormatDuration(const steady_clock::duration& dur)
{
return FormatDuration<DUNIT_US>(dur);
}
////////////////////////////////////////////////////////////////////////////////
//
// CGlobEvent class
//
////////////////////////////////////////////////////////////////////////////////
class CGlobEvent
{
public:
/// Triggers the event and notifies waiting threads.
/// Simply calls notify_one().
static void triggerEvent();
/// Waits for the event to be triggered with 10ms timeout.
/// Simply calls wait_for().
static bool waitForEvent();
};
////////////////////////////////////////////////////////////////////////////////
//
// CThread class
//
////////////////////////////////////////////////////////////////////////////////
#ifdef ENABLE_STDCXX_SYNC
typedef std::system_error CThreadException;
using CThread = std::thread;
#else // pthreads wrapper version
typedef ::CUDTException CThreadException;
class CThread
{
public:
CThread();
/// @throws std::system_error if the thread could not be started.
CThread(void *(*start_routine) (void *), void *arg);
#if HAVE_FULL_CXX11
CThread& operator=(CThread &other) = delete;
CThread& operator=(CThread &&other);
#else
CThread& operator=(CThread &other);
/// To be used only in StartThread function.
/// Creates a new stread and assigns to this.
/// @throw CThreadException
void create_thread(void *(*start_routine) (void *), void *arg);
#endif
public: // Observers
/// Checks if the CThread object identifies an active thread of execution.
/// A default constructed thread is not joinable.
/// A thread that has finished executing code, but has not yet been joined
/// is still considered an active thread of execution and is therefore joinable.
bool joinable() const;
struct id
{
explicit id(const pthread_t t)
: value(t)
{}
const pthread_t value;
inline bool operator==(const id& second) const
{
return pthread_equal(value, second.value) != 0;
}
};
/// Returns the id of the current thread.
/// In this implementation the ID is the pthread_t.
const id get_id() const { return id(m_thread); }
public:
/// Blocks the current thread until the thread identified by *this finishes its execution.
/// If that thread has already terminated, then join() returns immediately.
///
/// @throws std::system_error if an error occurs
void join();
public: // Internal
/// Calls pthread_create, throws exception on failure.
/// @throw CThreadException
void create(void *(*start_routine) (void *), void *arg);
private:
pthread_t m_thread;
};
template <class Stream>
inline Stream& operator<<(Stream& str, const CThread::id& cid)
{
#if defined(_WIN32) && defined(PTW32_VERSION)
// This is a version specific for pthread-win32 implementation
// Here pthread_t type is a structure that is not convertible
// to a number at all.
return str << pthread_getw32threadid_np(cid.value);
#else
return str << cid.value;
#endif
}
namespace this_thread
{
const inline CThread::id get_id() { return CThread::id (pthread_self()); }
inline void sleep_for(const steady_clock::duration& t)
{
#if !defined(_WIN32)
usleep(count_microseconds(t)); // microseconds
#else
Sleep(count_milliseconds(t));
#endif
}
}
#endif
/// StartThread function should be used to do CThread assignments:
/// @code
/// CThread a();
/// a = CThread(func, args);
/// @endcode
///
/// @returns true if thread was started successfully,
/// false on failure
///
#ifdef ENABLE_STDCXX_SYNC
typedef void* (&ThreadFunc) (void*);
bool StartThread(CThread& th, ThreadFunc&& f, void* args, const char* name);
#else
bool StartThread(CThread& th, void* (*f) (void*), void* args, const char* name);
#endif
////////////////////////////////////////////////////////////////////////////////
//
// CThreadError class - thread local storage wrapper
//
////////////////////////////////////////////////////////////////////////////////
/// Set thread local error
/// @param e new CUDTException
void SetThreadLocalError(const CUDTException& e);
/// Get thread local error
/// @returns CUDTException pointer
CUDTException& GetThreadLocalError();
} // namespace sync
} // namespace srt
#endif // INC_SRT_SYNC_H