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
|
/*
* 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/.
*
*/
#include "platform_sys.h"
#include <iomanip>
#include <stdexcept>
#include <cmath>
#include "sync.h"
#include "srt.h"
#include "srt_compat.h"
#include "logging.h"
#include "common.h"
// HAVE_CXX11 is defined in utilities.h, included with common.h.
// The following conditional inclusion must go after common.h.
#if HAVE_CXX11
#include <random>
#endif
namespace srt_logging
{
extern Logger inlog;
}
using namespace srt_logging;
using namespace std;
namespace srt
{
namespace sync
{
std::string FormatTime(const steady_clock::time_point& timestamp)
{
if (is_zero(timestamp))
{
// Use special string for 0
return "00:00:00.000000 [STDY]";
}
const int decimals = clockSubsecondPrecision();
const uint64_t total_sec = count_seconds(timestamp.time_since_epoch());
const uint64_t days = total_sec / (60 * 60 * 24);
const uint64_t hours = total_sec / (60 * 60) - days * 24;
const uint64_t minutes = total_sec / 60 - (days * 24 * 60) - hours * 60;
const uint64_t seconds = total_sec - (days * 24 * 60 * 60) - hours * 60 * 60 - minutes * 60;
ostringstream out;
if (days)
out << days << "D ";
out << setfill('0') << setw(2) << hours << ":"
<< setfill('0') << setw(2) << minutes << ":"
<< setfill('0') << setw(2) << seconds << "."
<< setfill('0') << setw(decimals) << (timestamp - seconds_from(total_sec)).time_since_epoch().count() << " [STDY]";
return out.str();
}
std::string FormatTimeSys(const steady_clock::time_point& timestamp)
{
const time_t now_s = ::time(NULL); // get current time in seconds
const steady_clock::time_point now_timestamp = steady_clock::now();
const int64_t delta_us = count_microseconds(timestamp - now_timestamp);
const int64_t delta_s =
static_cast<int64_t>(floor((static_cast<double>(count_microseconds(now_timestamp.time_since_epoch()) % 1000000) + delta_us) / 1000000.0));
const time_t tt = now_s + delta_s;
struct tm tm = SysLocalTime(tt); // in seconds
char tmp_buf[512];
strftime(tmp_buf, 512, "%X.", &tm);
ostringstream out;
out << tmp_buf << setfill('0') << setw(6) << (count_microseconds(timestamp.time_since_epoch()) % 1000000) << " [SYST]";
return out.str();
}
#ifdef ENABLE_STDCXX_SYNC
bool StartThread(CThread& th, ThreadFunc&& f, void* args, const string& name)
#else
bool StartThread(CThread& th, void* (*f) (void*), void* args, const string& name)
#endif
{
ThreadName tn(name);
try
{
#if HAVE_FULL_CXX11 || defined(ENABLE_STDCXX_SYNC)
th = CThread(f, args);
#else
// No move semantics in C++03, therefore using a dedicated function
th.create_thread(f, args);
#endif
}
#if ENABLE_HEAVY_LOGGING
catch (const CThreadException& e)
#else
catch (const CThreadException&)
#endif
{
HLOGC(inlog.Debug, log << name << ": failed to start thread. " << e.what());
return false;
}
return true;
}
} // namespace sync
} // namespace srt
////////////////////////////////////////////////////////////////////////////////
//
// CEvent class
//
////////////////////////////////////////////////////////////////////////////////
srt::sync::CEvent::CEvent()
{
#ifndef _WIN32
m_cond.init();
#endif
}
srt::sync::CEvent::~CEvent()
{
#ifndef _WIN32
m_cond.destroy();
#endif
}
bool srt::sync::CEvent::lock_wait_until(const TimePoint<steady_clock>& tp)
{
UniqueLock lock(m_lock);
return m_cond.wait_until(lock, tp);
}
void srt::sync::CEvent::notify_one()
{
return m_cond.notify_one();
}
void srt::sync::CEvent::notify_all()
{
return m_cond.notify_all();
}
bool srt::sync::CEvent::lock_wait_for(const steady_clock::duration& rel_time)
{
UniqueLock lock(m_lock);
return m_cond.wait_for(lock, rel_time);
}
bool srt::sync::CEvent::wait_for(UniqueLock& lock, const steady_clock::duration& rel_time)
{
return m_cond.wait_for(lock, rel_time);
}
void srt::sync::CEvent::lock_wait()
{
UniqueLock lock(m_lock);
return wait(lock);
}
void srt::sync::CEvent::wait(UniqueLock& lock)
{
return m_cond.wait(lock);
}
namespace srt {
namespace sync {
srt::sync::CEvent g_Sync;
} // namespace sync
} // namespace srt
////////////////////////////////////////////////////////////////////////////////
//
// Timer
//
////////////////////////////////////////////////////////////////////////////////
srt::sync::CTimer::CTimer()
{
}
srt::sync::CTimer::~CTimer()
{
}
bool srt::sync::CTimer::sleep_until(TimePoint<steady_clock> tp)
{
// The class member m_sched_time can be used to interrupt the sleep.
// Refer to Timer::interrupt().
enterCS(m_event.mutex());
m_tsSchedTime = tp;
leaveCS(m_event.mutex());
#if USE_BUSY_WAITING
#if defined(_WIN32)
// 10 ms on Windows: bad accuracy of timers
const steady_clock::duration
td_threshold = milliseconds_from(10);
#else
// 1 ms on non-Windows platforms
const steady_clock::duration
td_threshold = milliseconds_from(1);
#endif
#endif // USE_BUSY_WAITING
TimePoint<steady_clock> cur_tp = steady_clock::now();
while (cur_tp < m_tsSchedTime)
{
#if USE_BUSY_WAITING
steady_clock::duration td_wait = m_tsSchedTime - cur_tp;
if (td_wait <= 2 * td_threshold)
break;
td_wait -= td_threshold;
m_event.lock_wait_for(td_wait);
#else
m_event.lock_wait_until(m_tsSchedTime);
#endif // USE_BUSY_WAITING
cur_tp = steady_clock::now();
}
#if USE_BUSY_WAITING
while (cur_tp < m_tsSchedTime)
{
#ifdef IA32
__asm__ volatile ("pause; rep; nop; nop; nop; nop; nop;");
#elif IA64
__asm__ volatile ("nop 0; nop 0; nop 0; nop 0; nop 0;");
#elif AMD64
__asm__ volatile ("nop; nop; nop; nop; nop;");
#elif defined(_WIN32) && !defined(__MINGW32__)
__nop();
__nop();
__nop();
__nop();
__nop();
#endif
cur_tp = steady_clock::now();
}
#endif // USE_BUSY_WAITING
return cur_tp >= m_tsSchedTime;
}
void srt::sync::CTimer::interrupt()
{
UniqueLock lck(m_event.mutex());
m_tsSchedTime = steady_clock::now();
m_event.notify_all();
}
void srt::sync::CTimer::tick()
{
m_event.notify_one();
}
void srt::sync::CGlobEvent::triggerEvent()
{
return g_Sync.notify_one();
}
bool srt::sync::CGlobEvent::waitForEvent()
{
return g_Sync.lock_wait_for(milliseconds_from(10));
}
////////////////////////////////////////////////////////////////////////////////
//
// Random
//
////////////////////////////////////////////////////////////////////////////////
namespace srt
{
#if HAVE_CXX11
static std::mt19937& randomGen()
{
static std::random_device s_RandomDevice;
static std::mt19937 s_GenMT19937(s_RandomDevice());
return s_GenMT19937;
}
#elif defined(_WIN32) && defined(__MINGW32__)
static void initRandSeed()
{
const int64_t seed = sync::steady_clock::now().time_since_epoch().count();
srand((unsigned int) seed);
}
static pthread_once_t s_InitRandSeedOnce = PTHREAD_ONCE_INIT;
#else
static unsigned int genRandSeed()
{
// Duration::count() does not depend on any global objects,
// therefore it is preferred over count_microseconds(..).
const int64_t seed = sync::steady_clock::now().time_since_epoch().count();
return (unsigned int) seed;
}
static unsigned int* getRandSeed()
{
static unsigned int s_uRandSeed = genRandSeed();
return &s_uRandSeed;
}
#endif
}
int srt::sync::genRandomInt(int minVal, int maxVal)
{
// This Meyers singleton initialization is thread-safe since C++11, but is not thread-safe in C++03.
// A mutex to protect simultaneous access to the random device.
// Thread-local storage could be used here instead to store the seed / random device.
// However the generator is not used often (Initial Socket ID, Initial sequence number, FileCC),
// so sharing a single seed among threads should not impact the performance.
static sync::Mutex s_mtxRandomDevice;
sync::ScopedLock lck(s_mtxRandomDevice);
#if HAVE_CXX11
uniform_int_distribution<> dis(minVal, maxVal);
return dis(randomGen());
#else
#if defined(__MINGW32__)
// No rand_r(..) for MinGW.
pthread_once(&s_InitRandSeedOnce, initRandSeed);
// rand() returns a pseudo-random integer in the range 0 to RAND_MAX inclusive
// (i.e., the mathematical range [0, RAND_MAX]).
// Therefore, rand_0_1 belongs to [0.0, 1.0].
const double rand_0_1 = double(rand()) / RAND_MAX;
#else // not __MINGW32__
// rand_r(..) returns a pseudo-random integer in the range 0 to RAND_MAX inclusive
// (i.e., the mathematical range [0, RAND_MAX]).
// Therefore, rand_0_1 belongs to [0.0, 1.0].
const double rand_0_1 = double(rand_r(getRandSeed())) / RAND_MAX;
#endif
// Map onto [minVal, maxVal].
// Note. There is a minuscule probablity to get maxVal+1 as the result.
// So we have to use long long to handle cases when maxVal = INT32_MAX.
// Also we must check 'res' does not exceed maxVal,
// which may happen if rand_0_1 = 1, even though the chances are low.
const long long llMaxVal = maxVal;
const int res = minVal + static_cast<int>((llMaxVal + 1 - minVal) * rand_0_1);
return min(res, maxVal);
#endif // HAVE_CXX11
}
////////////////////////////////////////////////////////////////////////////////
//
// Shared Mutex
//
////////////////////////////////////////////////////////////////////////////////
srt::sync::SharedMutex::SharedMutex()
: m_LockWriteCond()
, m_LockReadCond()
, m_Mutex()
, m_iCountRead(0)
, m_bWriterLocked(false)
{
setupCond(m_LockReadCond, "SharedMutex::m_pLockReadCond");
setupCond(m_LockWriteCond, "SharedMutex::m_pLockWriteCond");
setupMutex(m_Mutex, "SharedMutex::m_pMutex");
}
srt::sync::SharedMutex::~SharedMutex()
{
releaseMutex(m_Mutex);
releaseCond(m_LockWriteCond);
releaseCond(m_LockReadCond);
}
void srt::sync::SharedMutex::lock()
{
UniqueLock l1(m_Mutex);
while (m_bWriterLocked)
m_LockWriteCond.wait(l1);
m_bWriterLocked = true;
while (m_iCountRead)
m_LockReadCond.wait(l1);
}
bool srt::sync::SharedMutex::try_lock()
{
UniqueLock l1(m_Mutex);
if (m_bWriterLocked || m_iCountRead > 0)
return false;
m_bWriterLocked = true;
return true;
}
void srt::sync::SharedMutex::unlock()
{
ScopedLock lk(m_Mutex);
m_bWriterLocked = false;
m_LockWriteCond.notify_all();
}
void srt::sync::SharedMutex::lock_shared()
{
UniqueLock lk(m_Mutex);
while (m_bWriterLocked)
m_LockWriteCond.wait(lk);
m_iCountRead++;
}
bool srt::sync::SharedMutex::try_lock_shared()
{
UniqueLock lk(m_Mutex);
if (m_bWriterLocked)
return false;
m_iCountRead++;
return true;
}
void srt::sync::SharedMutex::unlock_shared()
{
ScopedLock lk(m_Mutex);
m_iCountRead--;
SRT_ASSERT(m_iCountRead >= 0);
if (m_iCountRead < 0)
m_iCountRead = 0;
if (m_bWriterLocked && m_iCountRead == 0)
m_LockReadCond.notify_one();
}
int srt::sync::SharedMutex::getReaderCount() const
{
ScopedLock lk(m_Mutex);
return m_iCountRead;
}
|