[ create a new paste ] login | about

Link: http://codepad.org/jZZSdoxJ    [ raw code | fork ]

C++, pasted on Oct 6:
#include <windows.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
using namespace boost;


class CStopWatch
{
public:
	CStopWatch() 
		: m_startTime(0)
		, m_stopTime(0)
	{

	}

	void Start()
	{
		QueryPerformanceCounter((LARGE_INTEGER *)&m_startTime);
	}

	void Stop()
	{
		QueryPerformanceCounter((LARGE_INTEGER *)&m_stopTime);
	}

	double GetElapsedTime()
	{
		__int64 freq = 0;
		QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
		return (m_stopTime - m_startTime) * 1.0 / freq ;
	}

private:
	__int64 m_startTime;
	__int64 m_stopTime;
};


class __declspec(align(64)) CSharedData
{
public:
	CSharedData() : data1(0), data2(0), data3(0) {}

	__declspec(align(64)) 
		unsigned int data1;

	__declspec(align(64)) 
		unsigned int data2;

	__declspec(align(64)) 
		unsigned int data3;
};

CSharedData t;

void Increment(unsigned int &n) { n++; }

// Use a boost function to prevent compiler from optimizing 
// the increment away.
function<void (unsigned int &)> f = bind(Increment, _1);

void ThreadProc1()
{
	while(t.data1 < 0x0FFFFFFF) { f(t.data1); }
}
void ThreadProc2()
{
	while(t.data2 < 0x0FFFFFFF) { f(t.data2); }
}

void ThreadProc3()
{
	while(t.data3 < 0x0FFFFFFF) { f(t.data3); }
}

void main()
{
	CStopWatch sw;
	sw.Start();
	thread t1(bind(ThreadProc1));
	thread t2(bind(ThreadProc2));
	thread t3(bind(ThreadProc3));
	t1.join();
	t2.join();
	t3.join();
	sw.Stop();


	std::cout << t.data1 << " " << t.data2 << " "<< t.data3 << std::endl;
	std::cout << sw.GetElapsedTime() << std::endl;
}


Create a new paste based on this one


Comments: