Skip to content

Instantly share code, notes, and snippets.

@isayme
Created December 6, 2012 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isayme/4222072 to your computer and use it in GitHub Desktop.
Save isayme/4222072 to your computer and use it in GitHub Desktop.
利用linux线程亲和性绑定,使所有的core(指逻辑核而不是物理核)满负荷运行
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sched.h>
#include <pthread.h>
void test_proc(void *arg)
{
pid_t cur_tid = syscall(SYS_gettid);
cpu_set_t mask;
int cpu_seq = *(int *)arg;
int num = 0;
CPU_ZERO(&mask);
CPU_SET(cpu_seq, &mask);
if( sched_setaffinity(cur_tid, sizeof(mask), &mask ) == -1 )
{
printf("Could not set CPU Affinity CpuCore[%d]\n", cpu_seq);
}
while(1)num++;
}
int main()
{
int i;
int cpu_cores;
pthread_t tid;
cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
printf("cpu cores = %d\n", cpu_cores);
for (i = 0; i < cpu_cores; i++)
{
if (0 != pthread_create(&tid, NULL, (void*)test_proc, &i))
{
printf("pthread_create %d error\n", i);
}
sleep(1);
}
while(1)sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment