Can I bind POSIX thread to cpu core?

Dan Nelson dnelson at allantgroup.com
Sun Jun 28 20:44:52 UTC 2009


In the last episode (Jun 28):
> I have system with 4 core cpu. How can I bind POSIX thread to the one
> core?  I mean that this thread can be executed on the fixed core.

See the cpuset(2) and cpuset_setaffinity(2) manpages.  Something like this
should work:

#include <err.h>
#include <stdio.h>
#include <sys/param.h>
#include <sys/cpuset.h>

int main(void)
{
	int i;
	cpuset_t myset;

	/* Get CPU mask for the current thread */
	if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(myset), &myset) == -1)
		err(1, "getaffinity failed");

	/* Find first available CPU - don't assume CPU0 is always available */
	for (i = 0; i < CPU_SETSIZE; i++)
		if (CPU_ISSET(i, &myset))
			break; 

	if (i == CPU_SETSIZE)
		err(1, "Not allowed to run on any CPUs?  How did I print this, then?");

	/* Set new CPU mask */
	printf ("Setting affinity to CPU %d\n", i);
	CPU_ZERO(&myset);
	CPU_SET(i, &myset);

	if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(myset), &myset) == -1)
		warn("setaffinity failed");

	/* Do CPU-intensive stuff here */
	return 0;
}


-- 
	Dan Nelson
	dnelson at allantgroup.com


More information about the freebsd-hackers mailing list