-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstat_counter.cpp
82 lines (79 loc) · 1.88 KB
/
stat_counter.cpp
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
#include <iostream>
#include <stdlib.h>
#include "stat_counter.hpp"
/*
** Taolun Chai
*/
namespace base{
Stat_Counter::Stat_Counter():
max_thread_num_(16),
final_count_(0)
{
counter_p_ = new int* [max_thread_num_];
for(int i = 0; i < max_thread_num_; i++){
index_free_.push_back(i);
counter_p_[i] = NULL;
}
}
Stat_Counter::Stat_Counter(int max_thread_num):
max_thread_num_(max_thread_num),
final_count_(0)
{
counter_p_ = new int* [max_thread_num_];
for(int i = 0; i < max_thread_num_; i++){
index_free_.push_back(i);
counter_p_[i] = NULL;
}
}
Stat_Counter::~Stat_Counter(){
delete []counter_p_;
}
void Stat_Counter::inc_count(){
counter_++;
}
__thread int Stat_Counter::counter_;
int Stat_Counter::read_count(){
int sum;
this->spinlock_.lock();
sum = final_count_;
for(int i = 0 ; i < max_thread_num_; i++){
if(counter_p_[i]) sum += *counter_p_[i];
}
this->spinlock_.unlock();
return sum;
}
bool Stat_Counter::count_register_thread(){
this->spinlock_.lock();
if(index_free_.empty()){
this->spinlock_.unlock();
return false; // no free space available
}
// check whether the thread been register
if(pid_map_index_.find(pthread_self())!=pid_map_index_.end()){
std::cerr << "error! duplicate register" << std::endl;
exit(1);
}
// do the register
pid_map_index_[pthread_self()] = index_free_.back();
counter_p_[index_free_.back()] = &counter_;
counter_ = 0;
index_free_.pop_back();
this->spinlock_.unlock();
return true;
}
bool Stat_Counter::count_unregister_thread(){
this->spinlock_.lock();
map<int,int>::iterator it = pid_map_index_.find(pthread_self());
// not found this thread!!
if(it==pid_map_index_.end()){
std::cerr << "error! thread not registered!" << std::endl;
exit(1);
}
final_count_ += counter_;
counter_p_[it->second] = NULL;
index_free_.push_back(it->second);
pid_map_index_.erase(it);
this->spinlock_.unlock();
return true;
}
}