-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy paththreadid.hpp
52 lines (47 loc) · 990 Bytes
/
threadid.hpp
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
#ifndef threadid_hpp
#define threadid_hpp threadid_hpp
#include <mutex>
#include <set>
class thread_id_store {
static unsigned long max_id;
static std::set<unsigned long> orphans;
static std::mutex mutex;
typedef std::lock_guard<std::mutex> scoped_lock;
public:
static unsigned long get() {
scoped_lock lock(mutex);
if(orphans.empty()) {
max_id++;
return max_id;
} else {
auto first = orphans.begin();
auto result = *first;
orphans.erase(first);
return result;
}
}
static void free(unsigned long idx) {
scoped_lock lock(mutex);
if(idx == max_id) {
max_id--;
while(orphans.erase(max_id)) {
max_id--;
}
} else {
orphans.insert(idx);
}
}
};
class thread_id_t {
unsigned long id;
public:
operator unsigned long() {
return id;
}
thread_id_t() : id(thread_id_store::get()) {}
~thread_id_t() {
thread_id_store::free(id);
}
};
extern thread_local thread_id_t thread_id;
#endif // threadid_hpp