Debian Codegraph @

apps/verbose.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 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 #include "verbose.hpp"
12 #include "sync.h" // srt::sync
13
14 namespace Verbose
15 {
16 bool on = false;
17 std::ostream* cverb = &std::cerr;
18 srt::sync::Mutex vlock;
19
20 Log& Log::operator<<(LogNoEol)
21 {
22 noeol = true;
23 if (on)
24 {
25 (*cverb) << std::flush;
26 }
27 return *this;
28 }
29
30 Log& Log::operator<<(LogLock)
31 {
32 lockline = true;
33 return *this;
34 }
35
36 Log::~Log()
37 {
38 if (on && !noeol)
39 {
40 if (lockline)
41 {
42 // Lock explicitly, as requested, and wait for the opportunity.
43 vlock.lock();
44 }
45 else if (vlock.try_lock())
46 {
47 // Successfully locked, so unlock immediately, locking wasn't requested.
48 vlock.unlock();
49 }
50 else
51 {
52 // Failed to lock, which means that some other thread has locked it first.
53 // This means that some other thread wants to print the whole line and doesn't
54 // want to be disturbed during this process. Lock the thread then as this is
55 // the only way to wait until it's unlocked. However, do not block your printing
56 // with locking, because you were not requested to lock (treat this mutex as
57 // an entry semaphore, which may only occasionally block the whole line).
58 vlock.lock();
59 vlock.unlock();
60 }
61 (*cverb) << std::endl;
62
63 // If lockline is set, the lock was requested and WAS DONE, so unlock.
64 // Otherwise locking WAS NOT DONE.
65 if (lockline)
66 vlock.unlock();
67 }
68 }
69 }