#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include int num = 0; int test[65535]; int mess_rw(int data) { int i; while (1) { for (i = 0; i < (sizeof(test) / sizeof(test[0])); i++) { if (test[i] != data) test[i] = data; } } } void *test_thread(void *arg) { int cpu = *(int *)arg; cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu, &mask); if (!sched_setaffinity(0, sizeof(mask), &mask)) printf("thread %d: running on cpu %d\n", cpu, cpu); else printf("thread %d: fail to set CPU affinity\n", cpu); mess_rw(cpu); return NULL; } int main(int argc, char *argv[]) { num = sysconf(_SC_NPROCESSORS_CONF); pthread_t thread[num]; int id[num]; int i; printf("PID %d on system with %d processor(s)\n", getpid(), num); for (i = 0; i < num; i++) { id[i] = i; pthread_create(&thread[i], NULL, test_thread, (void *)&id[i]); } for (i = 0; i < num; i++) { pthread_join(thread[i], NULL); } return 0; }