Last active
September 4, 2020 14:54
-
-
Save planetA/10738756412cc411a7f9002fcb2639f4 to your computer and use it in GitHub Desktop.
Does sched_yield work?
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
CFLAGS=-pthread | |
all: test |
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 <pthread.h> | |
#include <sys/time.h> | |
#include <time.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <sys/resource.h> | |
const int n_iter = 100; | |
static void work_hostname(void) { | |
char buf[42]; | |
gethostname(buf, sizeof buf); | |
} | |
static void work_yield(void) { | |
sched_yield(); | |
} | |
static void * thread_start(void *arg) { | |
void (*work)(void) = arg; | |
struct timespec now; | |
long long int end; | |
clock_gettime(CLOCK_MONOTONIC, &now); | |
end = now.tv_sec * 1000000000 + now.tv_nsec + 1000000000lu*10; | |
while (1) { | |
clock_gettime(CLOCK_MONOTONIC, &now); | |
if (now.tv_sec * 1000000000 + now.tv_nsec > end) { | |
break; | |
} | |
for (int i = 0; i < n_iter; i ++) | |
work(); | |
} | |
struct rusage usage; | |
getrusage(RUSAGE_SELF, &usage); | |
printf("%s: USER: %lld SYS: %lld CTXSW: %ld INVCTXSW: %ld\n", | |
work == work_hostname ? "HOSTN" : "YIELD", | |
usage.ru_utime.tv_sec * 1000000 + usage.ru_utime.tv_usec, | |
usage.ru_stime.tv_sec * 1000000 + usage.ru_stime.tv_usec, | |
usage.ru_nvcsw, usage.ru_nivcsw); | |
return NULL; | |
} | |
int main() { | |
pthread_attr_t attr; | |
void *res; | |
pthread_t thread_id[2]; | |
int ret; | |
ret = pthread_attr_init(&attr); | |
ret = pthread_attr_setstacksize(&attr, 4096); | |
ret = pthread_create(&thread_id[0], &attr, thread_start, work_hostname); | |
ret = pthread_create(&thread_id[1], &attr, thread_start, work_yield); | |
ret = pthread_attr_destroy(&attr); | |
ret = pthread_join(thread_id[0], &res); | |
ret = pthread_join(thread_id[1], &res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment