Created
October 23, 2016 10:05
-
-
Save gnitnaw/d3572c7e90e07fc1b76d25d540be7f3d to your computer and use it in GitHub Desktop.
Example to limit the cpu affinity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdatomic.h> | |
#define __USE_GNU | |
#include <sched.h> | |
#include <pthread.h> | |
typedef struct { | |
char name[16]; | |
int sleepTime; | |
} Node; | |
void _usleep(int); | |
void* generateSingleThread(void*); | |
void printAndSleep(Node*); | |
atomic_int acnt; | |
int main(void) { | |
cpu_set_t cmask; | |
unsigned long len = sizeof(cmask); | |
CPU_ZERO(&cmask); /* 初始化 cmask */ | |
CPU_SET(0, &cmask); /* 指定第一個處理器 */ | |
/* 設定自己由指定的處理器執行 */ | |
if (sched_setaffinity(0, len, &cmask)) { | |
printf("Could not set cpu affinity for current process.\n"); | |
exit(1); | |
} | |
Node nodes[] = {{"One", 100000}, {"Two", 200000}, {"Three", 300000}}; | |
pthread_t thread[3]; | |
for (int i=0; i<3; ++i) { | |
pthread_create(&thread[i], NULL, generateSingleThread, (void*) &nodes[i]); | |
} | |
for (int i=0; i<3; ++i) pthread_join(thread[i],NULL); | |
return 0; | |
} | |
void* generateSingleThread(void* nodes) { | |
Node* node = (Node*)nodes; | |
for (int i=0; i<1000; ++i) { | |
while (acnt) sched_yield() ; | |
atomic_fetch_add(&acnt, 1); | |
printf("%dth Time: ", i); | |
atomic_fetch_sub(&acnt, 1); | |
printAndSleep(node); | |
} | |
pthread_exit(NULL); | |
} | |
void printAndSleep(Node* node) { | |
printf("%s\n", node->name); | |
_usleep(node->sleepTime); | |
} | |
void _usleep(int micro) | |
{ | |
struct timespec req = {0}; | |
req.tv_sec = 0; | |
req.tv_nsec = micro * 1000L; | |
nanosleep(&req, (struct timespec *)NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment