Created
February 5, 2013 21:37
-
-
Save drsnyder/4717947 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/*gcc -o t-poller t-poller.c -lpthread*/#include <stdio.h>#include <stdlib.h>#include <string.h> | |
#include <unistd.h> | |
#include <poll.h> | |
#include <pthread.h> | |
#include <sys/time.h> | |
#include <sys/resource.h> | |
#define THREADS 1000 | |
#define ITERATIONS 1000 | |
void * child(void * ptr) | |
{ | |
struct pollfd pfd; | |
struct rusage ru1, ru2; | |
int diff, total; | |
int fd = *(int*)ptr; | |
total = 0; | |
memset(&pfd, 0, sizeof(pfd)); | |
pfd.fd = fd; | |
pfd.events = 0; | |
while (write(fd, "foo\n", 4) == 4) { | |
getrusage(RUSAGE_SELF, &ru1); | |
if (poll(&pfd, 1, 100) != 0) | |
break; | |
getrusage(RUSAGE_SELF, &ru2); | |
diff = ru2.ru_nvcsw - ru1.ru_nvcsw; if (diff > 2) { | |
total += diff; | |
printf("volcs for poll() = %d\n", diff); | |
} | |
} | |
printf("%d exited. total %d\n", (int)getpid(), total); | |
fprintf(stderr, "%d\n", total); | |
return (void *)NULL; | |
} | |
int main(void) | |
{ | |
struct pollfd pfds[2]; | |
int i, iterations, fd[2]; | |
char buf[1024]; | |
pthread_t threads[THREADS]; | |
iterations = 0; | |
pipe(fd); | |
for (i = 0; i < THREADS; i++) { | |
pthread_create( &threads[i], NULL, child, (void *)&fd[1]); | |
} | |
memset(pfds, 0, sizeof(pfds)); | |
pfds[0].fd = 0; | |
pfds[0].events = POLLIN; | |
pfds[1].fd = fd[0]; | |
pfds[1].events = POLLIN; | |
while (poll(pfds, 2, -1) > 0) { | |
if (pfds[0].revents != 0) | |
break; | |
if (iterations >= ITERATIONS) | |
break; | |
if (pfds[1].revents != 0) | |
read(fd[0], buf, sizeof(buf)); | |
iterations++; | |
} | |
close(fd[0]); | |
close(fd[1]); | |
for (i = 0; i < THREADS; i++) { | |
pthread_join( threads[i], NULL); | |
} | |
printf("done\n"); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment