-
Notifications
You must be signed in to change notification settings - Fork 2
/
concurrency_limit.cc
42 lines (37 loc) · 991 Bytes
/
concurrency_limit.cc
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
#include "concurrency_limit.h"
#include <condition_variable>
#include <iostream>
#include <mutex>
using std::condition_variable;
using std::cout;
using std::lock_guard;
using std::mutex;
using std::set;
using std::string;
using std::unique_lock;
void ScopedConcurrencyLimit::DumpStatusLocked() const {
// TODO: assert lock is held.
string output;
for (const string* message : messages_) {
output += *message + " ";
}
output += " ";
cout << output.substr(0, 79) << "\r" << std::flush;
}
ScopedConcurrencyLimit::ScopedConcurrencyLimit(const string& message)
: message_(message) {
unique_lock<mutex> l(m_);
if (messages_.size() > kLimit) {
DumpStatusLocked();
cv_.wait(l, [] { return messages_.size() <= kLimit; });
}
messages_.insert(&message_);
}
ScopedConcurrencyLimit::~ScopedConcurrencyLimit() {
{
lock_guard<mutex> l(m_);
messages_.erase(&message_);
DumpStatusLocked();
}
cv_.notify_one();
}