+ for ( ;; ) {
+ int num_active = epoll_wait(ep_fd, events, epoll_room_in_receiver, -1);
+ if (num_active == -1) {
+ if (errno == EINTR)
+ continue;
+ perror("epoll_wait");
+ exit(1);
+ }
+
+ for (i = 0; i < num_active; ++i) {
+ int sock = events[i].data.fd;
+ int ret;
+ if (sock == server_sock) {
+ struct sockaddr_in addr;
+ int sock;
+ socklen_t addr_len = sizeof(addr);
+
+ sock = accept(server_sock, (struct sockaddr *)&addr, &addr_len);
+ if (sock == -1) {
+ if (errno == EAGAIN || errno == EINTR) {
+ // another thread snatched it, ignore
+ continue;
+ } else {
+ perror("accept()");
+ exit(1);
+ }
+ }
+
+ // add it to the epoll set
+ ev.events = EPOLLIN | EPOLLHUP | EPOLLERR;
+ ev.data.fd = sock;
+
+ if (epoll_ctl(ep_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
+ perror("EPOLL_CTL_ADD");
+ exit(1);
+ }
+ continue;
+ }
+
+ ret = read(sock, buf, 65536);
+ if (ret == 0) {
+ if (epoll_ctl(ep_fd, EPOLL_CTL_DEL, sock, NULL) == -1) {
+ perror("EPOLL_CTL_DEL");
+ exit(1);
+ }
+ close(sock);
+ continue;
+ }
+
+ bytes_received += ret;
+
+ // update the central counter after every 1MB (8ms
+ // at gigabit speeds, should be enough) of received data
+ if (bytes_received > update_frequency) {
+ pthread_mutex_lock(&receive_mutex);
+ total_bytes_received += bytes_received;
+ pthread_mutex_unlock(&receive_mutex);
+
+ bytes_received = 0;
+ }
+ }
+ }
+
+ pthread_mutex_lock(&receive_mutex);
+ total_bytes_received += bytes_received;
+ pthread_mutex_unlock(&receive_mutex);
+