读编程之美(一) 让cpu占用率听你指挥

实现对多核cpu的控制,一个画sin曲线,一个画直线。因为电脑的配置不同,可能结果不是很理想,调整程序中的时间参数就可以了。

#include <Windows.h>
#include <process.h>    //for 多线程
#include <math.h>
#include <iostream>
using namespace std;

void TimeSlice(int BusyTime, int IdleTime)
{
	int iStart = ::GetTickCount();
	while(::GetTickCount() - iStart < BusyTime);

	Sleep( IdleTime );
}

unsigned __stdcall DrawLine( LPVOID param )
{
	unsigned iDelay = reinterpret_cast<int>(param);
	double percentage = iDelay * 0.01;
	const int TotalTime = 30;
	int busyTime = static_cast<int>(TotalTime * percentage);
	int idleTime = TotalTime - busyTime;

	while (true)
	{
		TimeSlice( busyTime, idleTime );
	}

	return 0;
}

unsigned __stdcall DrawSin( LPVOID param )
{
	const double PI = 3.1415926;
	const int INTERVAL  = 200;
	const int COUNT = 100;
	const double SPLIT = 2.0 / COUNT;

	int half = static_cast<int>(INTERVAL * 0.5);
	int busySpan[COUNT];
	int idleSpan[COUNT];
	double radian = 0;
	for ( int i = 0; i < COUNT; i++ )
	{
		busySpan[i] = static_cast<int>(half + half * sin( radian * PI ));
		idleSpan[i] = INTERVAL - busySpan[i];
		radian += SPLIT;
	}

	int cnt = 0;
	while (true)
	{
		TimeSlice( busySpan[cnt], INTERVAL-busySpan[cnt] );
	
		cnt++;
		if (cnt == COUNT)
		{
			cnt = 0;
		}
	}

	return 0;
}

int main()
{
	SYSTEM_INFO info;
	GetSystemInfo(&info);
	cout << info.dwNumberOfProcessors << endl;
	cout << info.dwProcessorType << endl;

	unsigned param = 50;
	unsigned        tid;
	unsigned long thd1, thd2;

	for ( int i = 0; i < info.dwNumberOfProcessors; i++ )
	{
		unsigned long mark = 0x00000001 << i;
		if ( i % 2)
		{
			thd1 = _beginthreadex(NULL,
				0,
				DrawLine,
				(void *)param,
				0,
				&tid);
			SetThreadAffinityMask( (HANDLE)thd1, mark );
		}
		else
		{
			thd2 = _beginthreadex(NULL,
				0,
				DrawSin,
				NULL,
				0,
				&tid);
			SetThreadAffinityMask( (HANDLE)thd2, mark );
		}
	}

	Sleep(100000);

	if(thd1 != NULL)
	{
		CloseHandle((HANDLE)thd1);
	}

	if(thd2 != NULL)
	{
		CloseHandle((HANDLE)thd2);
	}
	
	return 0;
}


你可能感兴趣的:(多线程,编程,null,System)