Suppose that we have a counter that is incremented very frequently
but read out quite rarely.
As will become clear in
Section ,
it is helpful to implement such a counter using a per-CPU variable.
Such a variable can be defined as follows:
DEFINE_PER_THREAD(int, counter); |
The counter must be initialized as follows:
init_per_thread(counter, 0); |
A thread can increment its instance of this counter as follows:
__get_thread_var(counter)++; |
The value of the counter is then the sum of its instances. A snapshot of the value of the counter can thus be collected as follows:
for_each_thread(i) sum += per_thread(counter, i); |
Again, it is possible to gain a similar effect using other mechanisms, but per-thread variables combine convenience and high performance.