/*
* The following code use sched_setaffinity to set CPU mask
* it will fork process and each process will run on only one core
*
* you can read from /proc/cpuinfo to get the number of processor
*/
int setup_multicore(int n)
{
cpu_set_t *cpuset = CPU_ALLOC(n);
size_t size = CPU_ALLOC_SIZE(n);
CPU_ZERO_S(size, cpuset);
CPU_SET_S(0, size, cpuset);
if (sched_setaffinity(getpid(), size, cpuset) < 0) {
CPU_FREE(cpuset);
return -1;
}
pid_t pid = 0;
// fork a child for each core
for (int i = 1; i < n; ++i) {
pid = fork();
if (pid 0)
continue;
CPU_ZERO_S(size, cpuset);
CPU_SET_S(i, size, cpuset);
if (sched_setaffinity(getpid(), size, cpuset) < 0) {
CPU_FREE(cpuset);
return -1;
}
break;
}
CPU_FREE(cpuset);
}
2011年12月15日 星期四
[Linux] process use multi-core CPU
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言