Created
April 28, 2014 15:04
-
-
Save thynson/11374832 to your computer and use it in GitHub Desktop.
epoll behaviour test on multriple threads environment
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
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * | |
* This program explains the following behaviour of epoll: | |
* When multriple threads are waiting on same epoll instance simultaneously, | |
* I/O event raised from a file registered on the epoll instance with edge | |
* trigger mode cause exactly one thread to wake up; while with level trigger | |
* mode cause at least one thread to wake up, depends on the event-consuming | |
* time and the schedule of threads. | |
* | |
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * | |
* Compile this file with -DUSE_EDGE_TRIGGER to see the behaviour of edge | |
* trigger mode | |
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ | |
#include <sys/epoll.h> | |
#include <sys/eventfd.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <unistd.h> | |
int epfd; | |
int evfd; | |
void *routine(void *param) | |
{ | |
printf ("thread %p ready\n", param); | |
struct epoll_event epev; | |
epoll_wait(epfd, &epev, 1, -1); | |
eventfd_t result; | |
usleep(1); // simulating some operation before we actually cosuming the event | |
eventfd_read(evfd, &result); | |
printf ("thread %p notified\n", param); | |
return NULL; | |
} | |
int main() | |
{ | |
struct epoll_event epev; | |
int i; | |
epfd = epoll_create1(0); | |
evfd = eventfd(0, EFD_NONBLOCK); | |
epev.events = EPOLLIN; | |
#ifdef USE_EDGE_TRIGGER | |
epev.events |= EPOLLET; | |
#endif | |
epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &epev); | |
pthread_t tid[100]; | |
for (i = 0; i < 100; ++i) | |
pthread_create(tid + i, NULL, routine, tid + i); | |
printf ("notifying\n"); | |
usleep(100); | |
eventfd_write(evfd, 1); | |
for (i = 0; i < 100; ++i) | |
pthread_join(tid[i], NULL); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment