| 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 |
#include "platform_sys.h" |
| 11 |
|
| 12 |
#include <iomanip> |
| 13 |
#include <stdexcept> |
| 14 |
#include <cmath> |
| 15 |
#include "sync.h" |
| 16 |
#include "srt.h" |
| 17 |
#include "srt_compat.h" |
| 18 |
#include "logging.h" |
| 19 |
#include "common.h" |
| 20 |
|
| 21 |
// HAVE_CXX11 is defined in utilities.h, included with common.h. |
| 22 |
// The following conditional inclusion must go after common.h. |
| 23 |
#if HAVE_CXX11 |
| 24 |
#include <random> |
| 25 |
#endif |
| 26 |
|
| 27 |
namespace srt_logging |
| 28 |
{ |
| 29 |
extern Logger inlog; |
| 30 |
} |
| 31 |
using namespace srt_logging; |
| 32 |
using namespace std; |
| 33 |
|
| 34 |
namespace srt |
| 35 |
{ |
| 36 |
namespace sync |
| 37 |
{ |
| 38 |
|
| 39 |
std::string FormatTime(const steady_clock::time_point& timestamp) |
| 40 |
{ |
| 41 |
if (is_zero(timestamp)) |
| 42 |
{ |
| 43 |
// Use special string for 0 |
| 44 |
return "00:00:00.000000 [STDY]"; |
| 45 |
} |
| 46 |
|
| 47 |
const int decimals = clockSubsecondPrecision(); |
| 48 |
const uint64_t total_sec = count_seconds(timestamp.time_since_epoch()); |
| 49 |
const uint64_t days = total_sec / (60 * 60 * 24); |
| 50 |
const uint64_t hours = total_sec / (60 * 60) - days * 24; |
| 51 |
const uint64_t minutes = total_sec / 60 - (days * 24 * 60) - hours * 60; |
| 52 |
const uint64_t seconds = total_sec - (days * 24 * 60 * 60) - hours * 60 * 60 - minutes * 60; |
| 53 |
ostringstream out; |
| 54 |
if (days) |
| 55 |
out << days << "D "; |
| 56 |
out << setfill('0') << setw(2) << hours << ":" |
| 57 |
<< setfill('0') << setw(2) << minutes << ":" |
| 58 |
<< setfill('0') << setw(2) << seconds << "." |
| 59 |
<< setfill('0') << setw(decimals) << (timestamp - seconds_from(total_sec)).time_since_epoch().count() << " [STDY]"; |
| 60 |
return out.str(); |
| 61 |
} |
| 62 |
|
| 63 |
std::string FormatTimeSys(const steady_clock::time_point& timestamp) |
| 64 |
{ |
| 65 |
const time_t now_s = ::time(NULL); // get current time in seconds |
| 66 |
const steady_clock::time_point now_timestamp = steady_clock::now(); |
| 67 |
const int64_t delta_us = count_microseconds(timestamp - now_timestamp); |
| 68 |
const int64_t delta_s = |
| 69 |
static_cast<int64_t>(floor((static_cast<double>(count_microseconds(now_timestamp.time_since_epoch()) % 1000000) + delta_us) / 1000000.0)); |
| 70 |
const time_t tt = now_s + delta_s; |
| 71 |
struct tm tm = SysLocalTime(tt); // in seconds |
| 72 |
char tmp_buf[512]; |
| 73 |
strftime(tmp_buf, 512, "%X.", &tm); |
| 74 |
|
| 75 |
ostringstream out; |
| 76 |
out << tmp_buf << setfill('0') << setw(6) << (count_microseconds(timestamp.time_since_epoch()) % 1000000) << " [SYST]"; |
| 77 |
return out.str(); |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
#ifdef ENABLE_STDCXX_SYNC |
| 82 |
bool StartThread(CThread& th, ThreadFunc&& f, void* args, const string& name) |
| 83 |
#else |
| 84 |
bool StartThread(CThread& th, void* (*f) (void*), void* args, const string& name) |
| 85 |
#endif |
| 86 |
{ |
| 87 |
ThreadName tn(name); |
| 88 |
try |
| 89 |
{ |
| 90 |
#if HAVE_FULL_CXX11 || defined(ENABLE_STDCXX_SYNC) |
| 91 |
th = CThread(f, args); |
| 92 |
#else |
| 93 |
// No move semantics in C++03, therefore using a dedicated function |
| 94 |
th.create_thread(f, args); |
| 95 |
#endif |
| 96 |
} |
| 97 |
#if ENABLE_HEAVY_LOGGING |
| 98 |
catch (const CThreadException& e) |
| 99 |
#else |
| 100 |
catch (const CThreadException&) |
| 101 |
#endif |
| 102 |
{ |
| 103 |
HLOGC(inlog.Debug, log << name << ": failed to start thread. " << e.what()); |
| 104 |
return false; |
| 105 |
} |
| 106 |
return true; |
| 107 |
} |
| 108 |
|
| 109 |
} // namespace sync |
| 110 |
} // namespace srt |
| 111 |
|
| 112 |
//////////////////////////////////////////////////////////////////////////////// |
| 113 |
// |
| 114 |
// CEvent class |
| 115 |
// |
| 116 |
//////////////////////////////////////////////////////////////////////////////// |
| 117 |
|
| 118 |
srt::sync::CEvent::CEvent() |
| 119 |
{ |
| 120 |
#ifndef _WIN32 |
| 121 |
m_cond.init(); |
| 122 |
#endif |
| 123 |
} |
| 124 |
|
| 125 |
srt::sync::CEvent::~CEvent() |
| 126 |
{ |
| 127 |
#ifndef _WIN32 |
| 128 |
m_cond.destroy(); |
| 129 |
#endif |
| 130 |
} |
| 131 |
|
| 132 |
bool srt::sync::CEvent::lock_wait_until(const TimePoint<steady_clock>& tp) |
| 133 |
{ |
| 134 |
UniqueLock lock(m_lock); |
| 135 |
return m_cond.wait_until(lock, tp); |
| 136 |
} |
| 137 |
|
| 138 |
void srt::sync::CEvent::notify_one() |
| 139 |
{ |
| 140 |
return m_cond.notify_one(); |
| 141 |
} |
| 142 |
|
| 143 |
void srt::sync::CEvent::notify_all() |
| 144 |
{ |
| 145 |
return m_cond.notify_all(); |
| 146 |
} |
| 147 |
|
| 148 |
bool srt::sync::CEvent::lock_wait_for(const steady_clock::duration& rel_time) |
| 149 |
{ |
| 150 |
UniqueLock lock(m_lock); |
| 151 |
return m_cond.wait_for(lock, rel_time); |
| 152 |
} |
| 153 |
|
| 154 |
bool srt::sync::CEvent::wait_for(UniqueLock& lock, const steady_clock::duration& rel_time) |
| 155 |
{ |
| 156 |
return m_cond.wait_for(lock, rel_time); |
| 157 |
} |
| 158 |
|
| 159 |
void srt::sync::CEvent::lock_wait() |
| 160 |
{ |
| 161 |
UniqueLock lock(m_lock); |
| 162 |
return wait(lock); |
| 163 |
} |
| 164 |
|
| 165 |
void srt::sync::CEvent::wait(UniqueLock& lock) |
| 166 |
{ |
| 167 |
return m_cond.wait(lock); |
| 168 |
} |
| 169 |
|
| 170 |
namespace srt { |
| 171 |
namespace sync { |
| 172 |
|
| 173 |
srt::sync::CEvent g_Sync; |
| 174 |
|
| 175 |
} // namespace sync |
| 176 |
} // namespace srt |
| 177 |
|
| 178 |
//////////////////////////////////////////////////////////////////////////////// |
| 179 |
// |
| 180 |
// Timer |
| 181 |
// |
| 182 |
//////////////////////////////////////////////////////////////////////////////// |
| 183 |
|
| 184 |
srt::sync::CTimer::CTimer() |
| 185 |
{ |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
srt::sync::CTimer::~CTimer() |
| 190 |
{ |
| 191 |
} |
| 192 |
|
| 193 |
|
| 194 |
bool srt::sync::CTimer::sleep_until(TimePoint<steady_clock> tp) |
| 195 |
{ |
| 196 |
// The class member m_sched_time can be used to interrupt the sleep. |
| 197 |
// Refer to Timer::interrupt(). |
| 198 |
enterCS(m_event.mutex()); |
| 199 |
m_tsSchedTime = tp; |
| 200 |
leaveCS(m_event.mutex()); |
| 201 |
|
| 202 |
#if USE_BUSY_WAITING |
| 203 |
#if defined(_WIN32) |
| 204 |
// 10 ms on Windows: bad accuracy of timers |
| 205 |
const steady_clock::duration |
| 206 |
td_threshold = milliseconds_from(10); |
| 207 |
#else |
| 208 |
// 1 ms on non-Windows platforms |
| 209 |
const steady_clock::duration |
| 210 |
td_threshold = milliseconds_from(1); |
| 211 |
#endif |
| 212 |
#endif // USE_BUSY_WAITING |
| 213 |
|
| 214 |
TimePoint<steady_clock> cur_tp = steady_clock::now(); |
| 215 |
|
| 216 |
while (cur_tp < m_tsSchedTime) |
| 217 |
{ |
| 218 |
#if USE_BUSY_WAITING |
| 219 |
steady_clock::duration td_wait = m_tsSchedTime - cur_tp; |
| 220 |
if (td_wait <= 2 * td_threshold) |
| 221 |
break; |
| 222 |
|
| 223 |
td_wait -= td_threshold; |
| 224 |
m_event.lock_wait_for(td_wait); |
| 225 |
#else |
| 226 |
m_event.lock_wait_until(m_tsSchedTime); |
| 227 |
#endif // USE_BUSY_WAITING |
| 228 |
|
| 229 |
cur_tp = steady_clock::now(); |
| 230 |
} |
| 231 |
|
| 232 |
#if USE_BUSY_WAITING |
| 233 |
while (cur_tp < m_tsSchedTime) |
| 234 |
{ |
| 235 |
#ifdef IA32 |
| 236 |
__asm__ volatile ("pause; rep; nop; nop; nop; nop; nop;"); |
| 237 |
#elif IA64 |
| 238 |
__asm__ volatile ("nop 0; nop 0; nop 0; nop 0; nop 0;"); |
| 239 |
#elif AMD64 |
| 240 |
__asm__ volatile ("nop; nop; nop; nop; nop;"); |
| 241 |
#elif defined(_WIN32) && !defined(__MINGW32__) |
| 242 |
__nop(); |
| 243 |
__nop(); |
| 244 |
__nop(); |
| 245 |
__nop(); |
| 246 |
__nop(); |
| 247 |
#endif |
| 248 |
|
| 249 |
cur_tp = steady_clock::now(); |
| 250 |
} |
| 251 |
#endif // USE_BUSY_WAITING |
| 252 |
|
| 253 |
return cur_tp >= m_tsSchedTime; |
| 254 |
} |
| 255 |
|
| 256 |
|
| 257 |
void srt::sync::CTimer::interrupt() |
| 258 |
{ |
| 259 |
UniqueLock lck(m_event.mutex()); |
| 260 |
m_tsSchedTime = steady_clock::now(); |
| 261 |
m_event.notify_all(); |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
void srt::sync::CTimer::tick() |
| 266 |
{ |
| 267 |
m_event.notify_one(); |
| 268 |
} |
| 269 |
|
| 270 |
|
| 271 |
void srt::sync::CGlobEvent::triggerEvent() |
| 272 |
{ |
| 273 |
return g_Sync.notify_one(); |
| 274 |
} |
| 275 |
|
| 276 |
bool srt::sync::CGlobEvent::waitForEvent() |
| 277 |
{ |
| 278 |
return g_Sync.lock_wait_for(milliseconds_from(10)); |
| 279 |
} |
| 280 |
|
| 281 |
//////////////////////////////////////////////////////////////////////////////// |
| 282 |
// |
| 283 |
// Random |
| 284 |
// |
| 285 |
//////////////////////////////////////////////////////////////////////////////// |
| 286 |
|
| 287 |
namespace srt |
| 288 |
{ |
| 289 |
#if HAVE_CXX11 |
| 290 |
static std::mt19937& randomGen() |
| 291 |
{ |
| 292 |
static std::random_device s_RandomDevice; |
| 293 |
static std::mt19937 s_GenMT19937(s_RandomDevice()); |
| 294 |
return s_GenMT19937; |
| 295 |
} |
| 296 |
#elif defined(_WIN32) && defined(__MINGW32__) |
| 297 |
static void initRandSeed() |
| 298 |
{ |
| 299 |
const int64_t seed = sync::steady_clock::now().time_since_epoch().count(); |
| 300 |
srand((unsigned int) seed); |
| 301 |
} |
| 302 |
static pthread_once_t s_InitRandSeedOnce = PTHREAD_ONCE_INIT; |
| 303 |
#else |
| 304 |
|
| 305 |
static unsigned int genRandSeed() |
| 306 |
{ |
| 307 |
// Duration::count() does not depend on any global objects, |
| 308 |
// therefore it is preferred over count_microseconds(..). |
| 309 |
const int64_t seed = sync::steady_clock::now().time_since_epoch().count(); |
| 310 |
return (unsigned int) seed; |
| 311 |
} |
| 312 |
|
| 313 |
static unsigned int* getRandSeed() |
| 314 |
{ |
| 315 |
static unsigned int s_uRandSeed = genRandSeed(); |
| 316 |
return &s_uRandSeed; |
| 317 |
} |
| 318 |
|
| 319 |
#endif |
| 320 |
} |
| 321 |
|
| 322 |
int srt::sync::genRandomInt(int minVal, int maxVal) |
| 323 |
{ |
| 324 |
// This Meyers singleton initialization is thread-safe since C++11, but is not thread-safe in C++03. |
| 325 |
// A mutex to protect simultaneous access to the random device. |
| 326 |
// Thread-local storage could be used here instead to store the seed / random device. |
| 327 |
// However the generator is not used often (Initial Socket ID, Initial sequence number, FileCC), |
| 328 |
// so sharing a single seed among threads should not impact the performance. |
| 329 |
static sync::Mutex s_mtxRandomDevice; |
| 330 |
sync::ScopedLock lck(s_mtxRandomDevice); |
| 331 |
#if HAVE_CXX11 |
| 332 |
uniform_int_distribution<> dis(minVal, maxVal); |
| 333 |
return dis(randomGen()); |
| 334 |
#else |
| 335 |
#if defined(__MINGW32__) |
| 336 |
// No rand_r(..) for MinGW. |
| 337 |
pthread_once(&s_InitRandSeedOnce, initRandSeed); |
| 338 |
// rand() returns a pseudo-random integer in the range 0 to RAND_MAX inclusive |
| 339 |
// (i.e., the mathematical range [0, RAND_MAX]). |
| 340 |
// Therefore, rand_0_1 belongs to [0.0, 1.0]. |
| 341 |
const double rand_0_1 = double(rand()) / RAND_MAX; |
| 342 |
#else // not __MINGW32__ |
| 343 |
// rand_r(..) returns a pseudo-random integer in the range 0 to RAND_MAX inclusive |
| 344 |
// (i.e., the mathematical range [0, RAND_MAX]). |
| 345 |
// Therefore, rand_0_1 belongs to [0.0, 1.0]. |
| 346 |
const double rand_0_1 = double(rand_r(getRandSeed())) / RAND_MAX; |
| 347 |
#endif |
| 348 |
|
| 349 |
// Map onto [minVal, maxVal]. |
| 350 |
// Note. There is a minuscule probability to get maxVal+1 as the result. |
| 351 |
// So we have to use long long to handle cases when maxVal = INT32_MAX. |
| 352 |
// Also we must check 'res' does not exceed maxVal, |
| 353 |
// which may happen if rand_0_1 = 1, even though the chances are low. |
| 354 |
const long long llMaxVal = maxVal; |
| 355 |
const int res = minVal + static_cast<int>((llMaxVal + 1 - minVal) * rand_0_1); |
| 356 |
return min(res, maxVal); |
| 357 |
#endif // HAVE_CXX11 |
| 358 |
} |
| 359 |
|
| 360 |
#if defined(ENABLE_STDCXX_SYNC) && HAVE_CXX17 |
| 361 |
|
| 362 |
// Shared mutex imp not required - aliased from C++17 |
| 363 |
|
| 364 |
#else |
| 365 |
|
| 366 |
//////////////////////////////////////////////////////////////////////////////// |
| 367 |
// |
| 368 |
// Shared Mutex |
| 369 |
// |
| 370 |
//////////////////////////////////////////////////////////////////////////////// |
| 371 |
|
| 372 |
srt::sync::SharedMutex::SharedMutex() |
| 373 |
: m_LockWriteCond() |
| 374 |
, m_LockReadCond() |
| 375 |
, m_Mutex() |
| 376 |
, m_iCountRead(0) |
| 377 |
, m_bWriterLocked(false) |
| 378 |
{ |
| 379 |
setupCond(m_LockReadCond, "SharedMutex::m_pLockReadCond"); |
| 380 |
setupCond(m_LockWriteCond, "SharedMutex::m_pLockWriteCond"); |
| 381 |
setupMutex(m_Mutex, "SharedMutex::m_pMutex"); |
| 382 |
} |
| 383 |
|
| 384 |
srt::sync::SharedMutex::~SharedMutex() |
| 385 |
{ |
| 386 |
releaseMutex(m_Mutex); |
| 387 |
releaseCond(m_LockWriteCond); |
| 388 |
releaseCond(m_LockReadCond); |
| 389 |
} |
| 390 |
|
| 391 |
void srt::sync::SharedMutex::lock() |
| 392 |
{ |
| 393 |
UniqueLock l1(m_Mutex); |
| 394 |
while (m_bWriterLocked) |
| 395 |
m_LockWriteCond.wait(l1); |
| 396 |
|
| 397 |
m_bWriterLocked = true; |
| 398 |
|
| 399 |
while (m_iCountRead) |
| 400 |
m_LockReadCond.wait(l1); |
| 401 |
} |
| 402 |
|
| 403 |
bool srt::sync::SharedMutex::try_lock() |
| 404 |
{ |
| 405 |
UniqueLock l1(m_Mutex); |
| 406 |
if (m_bWriterLocked || m_iCountRead > 0) |
| 407 |
return false; |
| 408 |
|
| 409 |
m_bWriterLocked = true; |
| 410 |
return true; |
| 411 |
} |
| 412 |
|
| 413 |
void srt::sync::SharedMutex::unlock() |
| 414 |
{ |
| 415 |
ScopedLock lk(m_Mutex); |
| 416 |
m_bWriterLocked = false; |
| 417 |
|
| 418 |
m_LockWriteCond.notify_all(); |
| 419 |
} |
| 420 |
|
| 421 |
void srt::sync::SharedMutex::lock_shared() |
| 422 |
{ |
| 423 |
UniqueLock lk(m_Mutex); |
| 424 |
while (m_bWriterLocked) |
| 425 |
m_LockWriteCond.wait(lk); |
| 426 |
|
| 427 |
m_iCountRead++; |
| 428 |
} |
| 429 |
|
| 430 |
bool srt::sync::SharedMutex::try_lock_shared() |
| 431 |
{ |
| 432 |
UniqueLock lk(m_Mutex); |
| 433 |
if (m_bWriterLocked) |
| 434 |
return false; |
| 435 |
|
| 436 |
m_iCountRead++; |
| 437 |
return true; |
| 438 |
} |
| 439 |
|
| 440 |
void srt::sync::SharedMutex::unlock_shared() |
| 441 |
{ |
| 442 |
ScopedLock lk(m_Mutex); |
| 443 |
|
| 444 |
m_iCountRead--; |
| 445 |
|
| 446 |
SRT_ASSERT(m_iCountRead >= 0); |
| 447 |
if (m_iCountRead < 0) |
| 448 |
m_iCountRead = 0; |
| 449 |
|
| 450 |
if (m_bWriterLocked && m_iCountRead == 0) |
| 451 |
m_LockReadCond.notify_one(); |
| 452 |
|
| 453 |
} |
| 454 |
|
| 455 |
int srt::sync::SharedMutex::getReaderCount() const |
| 456 |
{ |
| 457 |
ScopedLock lk(m_Mutex); |
| 458 |
return m_iCountRead; |
| 459 |
} |
| 460 |
#endif // C++17 for shared_mutex |
| 461 |
|