refactoring - Refactor regular C++ code pattern -


summary: i'm trying see if can refactor c++ code has regular pattern make easier update , maintain.

details:

i have code creates thread local counters keep track of statistics during program execution. when statistic added source code there 5 things need updated: counter thread local declaration, counter total declaration, function reset thread counters, function add thread counters total, , print function.

the code following:

// adding statistic named 'counter'  // declaration of counter __thread int counter = 0; int total_counter = 0;  // in reset function counter = 0;  // in add function total_counter += counter;  // in print function printf("counter value is: %d\n", total_counter); 

i can see how macro created declaration of counter doing like:

#define stat(name) __thread int name; \                    int total_##name; 

but haven't thought of how extended update add , reset functions. ideally i'd type stat(counter) , have declarations , functions managing statistic taken care of.

edit:

i have macros updating statistics in code. something stat_inc(counter) increment local counter value. when thread finished execution it's thread local values added overall total. name of each statistic important why array not work me. because real counter names things cache_hit more meaningful counter[2] , don't want lose ability have arbitrary names statistics created. simplify amount of code have write when declaring statistic if possible.

this keeps more or less described in question encapsulated in template class:

enum statnames {     stat_rx_bytes,     stat_tx_bytes,     //..., };  template <statnames sn> class stat {     static const char *name_;     static __thread int x_;     static int total_;  public:     stat(const char *name) { name_ = name; }     static void reset () { x_ = 0; }     static void add () { total_ += x_; }     static void print () {         std::cout << name_ << " value is: " << total_ << "\n";     }     static int & x () { return x_; }     static int total () { return total_; } };  template <statnames sn> const char * stat<sn>::name_; template <statnames sn> __thread int stat<sn>::x_; template <statnames sn> int stat<sn>::total_;  #define stat(name) stat<stat_##name> name(#name) 

you write code following:

stat(rx_bytes);  void * test (void *) {     rx_bytes.x() += 4;     rx_bytes.add();     std::cout << pthread_self() << ": " << rx_bytes.x() << "\n";     return 0; }  int main () {     pthread_t t[2];     pthread_create(&t[0], 0, test, 0);     pthread_create(&t[1], 0, test, 0);     pthread_join(t[0], 0);     pthread_join(t[1], 0);     rx_bytes.print(); } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -