Skip to content

Instantly share code, notes, and snippets.

@Lazin
Created June 1, 2012 08:45
Show Gist options
  • Save Lazin/2850441 to your computer and use it in GitHub Desktop.
Save Lazin/2850441 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <windows.h>
#include <boost/thread.hpp>
class ConcurrentCounter {
unsigned int* counters_;
int length_;
public:
ConcurrentCounter() {
length_ = boost::thread::hardware_concurrency() * 0x100;
counters_ = new unsigned int[length_];
std::fill(counters_, counters_ + length_, 0);
}
unsigned int get_value() {
return std::accumulate(counters_, counters_ + length_, 0);
}
void inc() {
auto i = rand() % length_;
InterlockedIncrement(counters_ + i);
}
};
int main(int argc, char* argv[])
{
{
boost::thread_group tg;
boost::barrier bar(4);
unsigned int counter = 0;
unsigned long startTime = 0;
unsigned long stopTime = 0;
auto threadFn = [&counter, &bar, &startTime] () {
bar.wait();
startTime = GetTickCount();
for(int i = 0; i < 0x1000000; i++)
InterlockedIncrement(&counter);
};
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.join_all();
stopTime = GetTickCount();
printf("counter - %d\n", counter);
printf("ticks - %d\n", stopTime - startTime);
}
{
boost::thread_group tg;
boost::barrier bar(4);
ConcurrentCounter counter;
unsigned long startTime = 0;
unsigned long stopTime = 0;
auto threadFn = [&counter, &bar, &startTime] () {
bar.wait();
startTime = GetTickCount();
for(int i = 0; i < 0x1000000; i++)
counter.inc();
};
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.create_thread(threadFn);
tg.join_all();
stopTime = GetTickCount();
printf("counter - %d\n", counter.get_value());
printf("ticks - %d\n", stopTime - startTime);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment