The 
legend of ROGER CLARK

Snippets/AffinityLauncher

The Windows Task Manager allows you to set a process's CPU affinity while it's running, but if it's already created threads that are running on a certain CPU, they'll continue to run on that CPU until they exit.

This utility will spawn a process, from the start, with a specified CPU affinity mask. You can use this to control which processor or processors a program and its threads run on. This can be useful for disabling the use of a number of cores for a specific application or to partition your applications up among your CPUs, acting as a guide to your scheduler. It's not particularly useful except in odd circumstances, but it's interesting nonetheless.

The program creates a process with the main thread in a suspended state, uses an array of 32 checkboxes to compose a 32-bit affinity mask for your process, sets the process affinity mask, and then unsuspends the main thread. Pretty simple. The meat of the utility is in this code:

if (CreateProcess(szPath, szArguments, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, szWorkingDir, &info, &psinfo))
{
	if (SetProcessAffinityMask(psinfo.hProcess, dwAffinity))
	{
		if (ResumeThread(psinfo.hThread) == 0xFFFFFFFF)
		{
			DisplayErrorMessage(hDlg, _T("ResumeThread failed"), GetLastError());
		}
		else
		{
			EndDialog(hDlg, LOWORD(wParam));
		}
	}
	else
	{
		DisplayErrorMessage(hDlg, _T("SetProcessAffinityMask failed"), GetLastError());
	}
}
else
{
	DisplayErrorMessage(hDlg, _T("CreateProcess failed"), GetLastError());
}

The full source code and project file can be found here:

Edit this page. Last modified on March 20, 2008, at 04:26 AM EST.
Copyright © 2007 Roger Clark.